Get ViewGroup (layout) of custom view

I made my own kind called ColorPicker. I am creating my ColorPicker in my xml.

<?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 Constr, I need a reference to my LinearLayout, but I cannot find any answer here.

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

    //LinearLayout layout = ???;
}

      

I've tried the following solutions I've read on similar questions:

getParent();

      

returns null

getRootView();

      

returns the ColorPicker itself

findViewByID(R.id.linearlayout_settings);

      

returns null

thanks in advance

+3


source to share


2 answers


The problem is that you are calling getParent()

inside your constructor View

, at this point has View

not been bound to the parent object. If you want to get the parent and make sure it is not null, override your customView

protected 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
    }
}

      

+1


source


Use the Color Dialog This is best for the selection color in the action colorDialog.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

Try it.

-1


source







All Articles