簡體   English   中英

獲取自定義視圖的ViewGroup(布局)

[英]Get ViewGroup(Layout) of custom view

我制作了一個名為ColorPicker的自定義視圖。 我在我的xml中創建了我的ColorPicker。

<?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的Constr我需要一個參考我的LinearLayout,但我在這里找不到任何答案。

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

    //LinearLayout layout = ???;
}

我嘗試了以下類似問題的解決方案:

getParent();

返回null

getRootView();

返回ColorPicker本身

findViewByID(R.id.linearlayout_settings);

返回null

提前致謝

問題是您在View的構造函數中調用了getParent() ,此時View尚未附加到父級。 如果您想獲取父級並確保它不為null,請覆蓋自定義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
    }
}

使用顏色對話框這樣更好用於在活動顏色上選擇顏色顏色.Dialog.setPickerColor(YourActivity.this,2,color);

要么

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

在Java文件中創建對象在java文件中查找對象

試試吧。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM