Android 以编程方式设置自定义视图的高度和宽度 [英] Android set height and width of Custom view programmatically
问题描述
我创建了一个名为 Graphview
的自定义视图.这是 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);
........
}
..................
.................
}
我使用 addview()
在表格行中添加了视图.它工作正常.现在我想为 GraphView
设置高度和宽度.怎么做?
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?
推荐答案
如果您知道视图的确切大小,只需使用 setLayoutParams()
:
If you know the exact size of the view, just use setLayoutParams()
:
graphView.setLayoutParams(new LayoutParams(width, height));
或者在 Kotlin 中:
Or in Kotlin:
graphView.layoutParams = LayoutParams(width, height)
但是,如果您需要更灵活的方法,您可以重写 onMeasure()
以根据可用空间和布局约束更精确地测量视图 (wrap_content
, match_parent
,或固定大小).您可以在 android 文档.
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 about onMeasure()
in the android docs.
这篇关于Android 以编程方式设置自定义视图的高度和宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!