這是我的自定義視圖:自定義視圖不添加子視圖
public class FilterView extends RelativeLayout{
public FilterView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public void init(){
//To test, I add just a test button that will change the color of the view
Button b = new Button(getContext());
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) { setBackgroundColor(Color.GREEN); }
});
b.setText("TEST");
RelativeLayout.LayoutParams lay = new RelativeLayout.LayoutParams(100, 100);
addView(b, lay);
//Also have tried without settings the layoutparams...
setBackgroundColor(Color.BLUE);
}
}
我在這樣一個活動添加該自定義視圖(紅色背景):
<com.example.android.FilterView android:id="@+id/filter"
android:layout_width="100dip"
android:background="#FF0000"
android:layout_height="100dip"/>
結果是一個視圖顏色...... BLUE,是在init()中設置的,所以init中的代碼被調用的很好。但認爲沒有什麼內部,它只是藍色的,沒有按鈕和一個名爲「TEST」,而且無論我點擊
也許你正在你的佈局之外增加你的按鈕(您的設備將具有非常低的DPI在這種情況下,雖然)。嘗試調用只是'addView(b);'而不是'addView(b,lay);' – velis
其實addView(b)是我最初,並沒有工作要麼 – Corbella