Mat Whiteside Mat Whiteside - 4 months ago 8
Android Question

Creating a custom menu using a layout inflator, how do I reference each component?

This is the item I'm inflating:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="@drawable/background_border"
android:padding="10dp"
>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Account name"
android:textSize="25sp"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Balance: £61.43"
android:textSize="25sp"
android:paddingTop="40dp"/>

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_keyboard_arrow_right_black_24dp"
android:layout_alignParentEnd="true"
android:layout_centerInParent="true"/>

</RelativeLayout>


And I'm inflating it using the following code:

LinearLayout parent = (LinearLayout) findViewById(R.id.linearL);

view = getLayoutInflater().inflate(R.layout.menu_item, parent,false);
parent.addView(view);


Say if I inflated the following item three times, to create three menu items - how would I reference each item individually?

For example, if I wanted to change the text of the Account name in the first item of the menu, how would I reference that it's in the first item of the menu, instead of the second or third?

Answer

Say if I inflated the following item three times, to create three menu items - how would I reference each item individually?

Use parent.getChildCount() and parent.getChildAt() for accessing Views from any R.layout.menu_item layout like:

Add layout multiple times:

//First time
parent.addView(view);
//Second time
parent.addView(view);

Get first added R.layout.menu_item layout view:

View firstView=parent.getChildAt(0);

In same way get other child View of parent layout.

Access child Views from firstView using :

View id if added in xml:

TextView textView=(TextView)firstView.findViewById(R.id.textViewID);

or using getChildAt method:

TextView textView=(TextView)firstView.getChildAt(0);

Access other views in same way.

Comments