Skip to content Skip to sidebar Skip to footer

How Do I Access The Views Inside The Layout When I Reuse It Multiple Times?

I have read the Android UI trick 2 on Android developers, which tells people how to include a layout in another layout file multiple times, and give these included layouts differen

Solution 1:

Say you want to include this:

<LinearLayout
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:orientation="horizontal"
>
    <ImageView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:src="@drawable/some_image"
    />
    <TextView
        android:id="@+id/included_text_view"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
    />
</LinearLayout>

so in your code you insert it like this:

<LinearLayout
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:orientation="vertical"
>
    <include android:id="@+id/header_1" layout="@layout/name_of_layout_xml" />
    <include android:id="@+id/header_2" layout="@layout/name_of_layout_xml" />
</LinearLayout>

now you want to access the text views within the included layouts to set the text dynamically. In your code you simply type:

LinearLayout ll = (LinearLayout)findViewById(R.id.header_1);
TextView tv = (TextView)ll.findViewById(R.id.included_text_view);
tv.setText("Header Text 1");

ll = (LinearLayout)findViewById(R.id.header_2);
tv = (TextView)ll.findViewById(R.id.included_text_view);
tv.setText("Header Text 2");

notice that you use the individual LinearLayouts' findViewById methods to narrow the search to only their children.


Solution 2:

I wanted to create TableRow layout and wanted to reuse it to my code in for loop. I was searching for the problem and at last found solution.

        TableLayout table = (TableLayout) findViewById(R.id.listTable);
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        ImageButton[] button = new ImageButton[4];
        TableRow[] row = new TableRow[4];

        for(int i =0 ; i<4;i++){

                row[i] = (TableRow) inflater.inflate(R.layout.list_row, null);
                table.addView(row[i]);
                button[i] = (ImageButton)row[i].findViewById(R.id.editBtn);
                button[i].setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        Log.i(TAG,"Button Clicked");
                    }
                });

This way you can achieve the functionality of reusing the layout and also can access inner elements


Post a Comment for "How Do I Access The Views Inside The Layout When I Reuse It Multiple Times?"