2014-02-28 46 views
1

這是我的自定義視圖:自定義視圖不添加子視圖

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」,而且無論我點擊

+0

也許你正在你的佈局之外增加你的按鈕(您的設備將具有非常低的DPI在這種情況下,雖然)。嘗試調用只是'addView(b);'而不是'addView(b,lay);' – velis

+0

其實addView(b)是我最初,並沒有工作要麼 – Corbella

回答

5

對不起,我做了一個可怕的錯誤,

我的自定義視圖中重新實現onLayout方法,並沒有調用它的超級方法...添加超級解決它。很抱歉打擾你,這麼愚蠢的問題..

@Override 
protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 
    super.onLayout(changed, left, top, right, bottom); 
} 
+0

很高興您對問題進行了排序,請接受此答案(當SO讓你這樣做時:P) –

0

完成此行

addView(b, lay); 

沒有區域是可點擊因爲視圖不翻綠
this.addView(b, lay); 
+0

不工作,同樣的問題 – Corbella

+0

並嘗試添加layaddRule(RelativeLayout.CENTER_IN_PARENT); –

+0

沒有運氣,沒有工作要麼 – Corbella

相關問題