2017-06-04 91 views
3

我製作了一個名爲ColorPicker的自定義視圖。我在我的xml中創建了我的ColorPicker。獲取自定義視圖的ViewGroup(佈局)

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:id="@+id/linearlayout_settings"> 

    <visuals.customview.ColorPicker 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" /> 
</LinearLayout> 

ColorPicker中的構造方法,我需要一個裁判我的LinearLayout,但我不能在這裏找到任何答案。

public ColorPicker(Context context, AttributeSet attrs) { 
    super(context, attrs); 

    //LinearLayout layout = ???; 
} 

我試過下面,我讀了類似的問題的解決方案:

getParent(); 

返回null

getRootView(); 

返回顏色拾取本身

findViewByID(R.id.linearlayout_settings); 

返回空

感謝的提前

回答

1

問題是您在View的構造函數中調用getParent(),此時View尚未附加到父項。如果你想獲得父母和確保它不爲空,覆蓋您的自定義Viewprotected void onAttachedToWindow()

public class ColorPicker extends View { 

    public ColorPicker(Context context, AttributeSet attrs) { 
     super(context, attrs);  
    } 

    @Override 
    protected void onAttachedToWindow() { 
     super.onAttachedToWindow();  
     // call getParent() here 
    } 
} 
+0

這是一種明顯的......非常感謝你的幫助,現在的工作:d – mesinger

-1

使用顏色對話框 這更好的有關活動 colorDialog.setPickerColor(YourActivity.this,2色)挑顏色;

OR

<visuals.customview.ColorPicker 
    android:layout_width="wrap_content" 
    android:id="@+id/vis1" 
    android:layout_height="wrap_content" /> 

創建對象的Java文件 找對象的Java文件

試試吧。

相關問題