我已經定製了擴展ViewGroup
類的類。在它裏面,我想添加一些視圖,包括兩個必須相鄰的按鈕。我想出了使用這個視圖創建XML文件的想法,然後使用addView添加它。不幸的是它不能解決問題。將LinearLayout添加到ViewGroup
我認爲更好的第二個想法是創建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));
}
}
總的來說,我只是用巨大的表,其中我有什麼樣的信息給出確切尺寸應該是視角。
這將有助於看到代碼爲您定製'ViewGroup'的'onMeasure'和'onLayout'方法。 – Luksprog
@Luksprog剛剛添加。 – sebap123
爲什麼你首先從xml加載兩個按鈕的想法不起作用? –