Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Attributes to Child View in Compound Views

I'm trying to make a compound view, whereby I can set attributes in XML and have them be passed to the children in the compound view. In the code below, I want to set the android:text and have it passed to the EditText.

Is this possible without having to set every attribute as a custom attribute?

Activity.xml:

<FrameLayout
     android:layout_width="match_parent"
     android:layout_height="wrap_content"/>
        <com.app.CustomLayout
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:text="child_view_text" />
</FrameLayout>

custom_view.xml:

<merge xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.TextInputLayout
        android:id="@+id/textInputLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <EditText
            android:id="@+id/editText"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </android.support.design.widget.TextInputLayout>
</merge>

CustomView.java:

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

private void init(Context context, AttributeSet attrs) {
    View v = inflate(context, R.layout.custom_view, this);

    mEditText = (EditText) v.findViewById(R.id.editText);
    mTextInputLayout = (TextInputLayout) findViewById(R.id.textInputLayout);
}
like image 836
soundsofpolaris Avatar asked Jan 31 '16 05:01

soundsofpolaris


1 Answers

Instead of having the EditText inside CustomLayout.xml you can instantiate it in CustomView.java passing the AttributeSet:

public class ValidationTextInputLayout extends LinearLayout
{
    public ValidationTextInputLayout(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs)
    {
        View v = inflate(context, R.layout.custom_view, this);

        mTextInputLayout = (TextInputLayout)findViewById(R.id.textInputLayout);

        mEditText = new EditText(context, attrs);
        mTextInputLayout.AddView(mEditText);
    }

    /* Properties etc... */
}

For anyone still having this issue.

like image 165
Daniel Avatar answered Oct 12 '22 15:10

Daniel