我有自定义类正在扩展ViewGroup
类。在里面我想添加一些视图,包括两个必须相邻的按钮。我想出了用这个视图创建 XML 文件然后使用 addView 添加它的想法。不幸的是,它没有成功。
我认为更好的第二个想法是以编程方式创建 LineraLayout 以及两个按钮,设置所有设置然后添加。
这是代码:
//adding view to view group
addView(createView(ctx));
//function creating linearlayout and buttons
private View createView(Context ctx){
LinearLayout l = new LinearLayout(ctx);
l.setOrientation(LinearLayout.HORIZONTAL);
l.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
Button btnL = new Button(ctx);
btnL.setText("Text1");
Button btnR = new Button(ctx);
btnR.setText("Text2");
l.addView(btnL);
l.addView(btnR);
return l;
}
问题是,我现在根本看不到这种观点。我的意思是这是从 LinearLayout 创建的。LogCat 中没有错误。
有人可以告诉我我必须做什么才能添加它吗?
编辑:
这是代码onLayout
,我没有onMeasure
:
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int w = getWidth();
int h = getHeight();
for (int i = 0; i < NUM_CHILDREN; i++) {
View v = getChildAt(i);
int ii = i * 4;
float fl = w * COORDS[ii] / GRID_WIDTH;
float ft = h * COORDS[ii + 1] / GRID_HEIGHT;
float fr = fl + w * COORDS[ii + 2] / GRID_WIDTH;
float fb = ft + h * COORDS[ii + 3] / GRID_HEIGHT;
v.layout(Math.round(fl), Math.round(ft), Math.round(fr),
Math.round(fb));
}
}
一般来说,我只是使用巨大的表格,在那里我可以获得给定视图的确切尺寸应该是什么信息。