简体   繁体   English

获取自定义视图的ViewGroup(布局)

[英]Get ViewGroup(Layout) of custom view

I made a custom View, called ColorPicker. 我制作了一个名为ColorPicker的自定义视图。 I create my ColorPicker in my xml. 我在我的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>

In the ColorPicker's Constr i need a ref to my LinearLayout, but i can't find any answer here. 在ColorPicker的Constr我需要一个参考我的LinearLayout,但我在这里找不到任何答案。

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

    //LinearLayout layout = ???;
}

I tried following solutions which i read on similar questions: 我尝试了以下类似问题的解决方案:

getParent();

returns null 返回null

getRootView();

returns the ColorPicker itself 返回ColorPicker本身

findViewByID(R.id.linearlayout_settings);

returns null 返回null

Thank's in advance 提前致谢

The problem is that you're calling getParent() inside your View 's constructor, at that point the View has not been attached to the parent. 问题是您在View的构造函数中调用了getParent() ,此时View尚未附加到父级。 If you want to get the parent and be sure it is not null, override your custom View 's protected void onAttachedToWindow() 如果您想获取父级并确保它不为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
    }
}

Use The Color Dialog Box This Better For pick color on Activity colorDialog.setPickerColor(YourActivity.this, 2, color); 使用颜色对话框这样更好用于在活动颜色上选择颜色颜色.Dialog.setPickerColor(YourActivity.this,2,color);

OR 要么

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

Create Object in Java File find object in java file 在Java文件中创建对象在java文件中查找对象

Try it. 试试吧。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM