Android 以编程方式设置自定义视图的高度和宽度
我创建了一个名为 Graphview 的自定义视图。这是 GraphView 类的结构。
public class GraphView extends View {
public GraphView(Context context, float[] values, String title, String[] horlabels, String[] verlabels, boolean type) {
super(context);
........
}
..................
.................
}
我已使用 addview()
在表行中添加了视图。它运行良好。现在我想设置 GraphView 的高度和宽度。怎么做呢?
I have created a custom view named Graphview
. Here is the structure for the GraphView class.
public class GraphView extends View {
public GraphView(Context context, float[] values, String title, String[] horlabels, String[] verlabels, boolean type) {
super(context);
........
}
..................
.................
}
I have added the view in a tablerow using addview()
. It is working fine. Now I want to set height and width for the GraphView
. How to do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
您可以像这样设置高度和宽度:
You can set height and width like this:
如果您知道视图的确切大小,只需使用
setLayoutParams()
:或者在 Kotlin 中:
但是,如果您需要更灵活的方法,您可以重写
onMeasure()
来根据可用空间和布局约束(wrap_content
、match_parent
或固定大小)更精确地测量视图。您可以在 Android 文档。If you know the exact size of the view, just use
setLayoutParams()
:Or in Kotlin:
However, if you need a more flexible approach you can override
onMeasure()
to measure the view more precisely depending on the space available and layout constraints (wrap_content
,match_parent
, or a fixed size). You can find more details aboutonMeasure()
in the android docs.您可以在相对布局中设置视图的高度和宽度,如下所示
you can set the height and width of a view in a relative layout like this
如果您使用 Kotlin,还可以使用以下代码将给定的 lambda 应用于当前布局参数:
If you're using Kotlin, you can also use the following code which applies your given lambda on the current layout params:
在 Kotlin 上,您可以直接使用虚拟属性设置任何视图的宽度和高度:
On Kotlin you can set width and height of any view directly using their virtual properties:
spin12
是您的微调器,200、120 是您的宽度
和高度
代码>微调器。spin12
is your spinner and 200,120 iswidth
andheight
for yourspinner
.这是基于 Kotlin 的版本,假设父视图是 LinearLayout 的实例。
这允许在一行中设置宽度和高度(
100
和200
)。This is a Kotlin based version, assuming that the parent view is an instance of
LinearLayout
.This allows to set the width and height (
100
and200
) in a single line.典型的现实世界示例:
在片段中:
getActivity()
LayoutParams
(即示例中的LinearLayout.LayoutParams
Typical real-world example:
in a Fragment:
getActivity()
LayoutParams
(ie,LinearLayout.LayoutParams
in the example添加到@MorganWilde 的解决方案中。如果要使用WRAP_CONTENT/MATCH_PARENT,可以使用以下代码。
Adding on to the solution by @MorganWilde. You can use the following code if you want to use WRAP_CONTENT/MATCH_PARENT.
这里这个类负责以编程方式处理视图所需的一切
}
,您可以像这样使用它:
here this class take care of everything you need for working with views programmatically
}
and you can use it like this: