Search code examples
androidandroid-relativelayout

Accessing Android Views in Java files


I've designed a RelativeLayout with children elements such as TextView and ImageView. What I want to do is to create a RelativeLayout object from my created RelativeLayout in XML, that way I can access to its children elements and modify them (change image from ImageView and change the text from TextView). How can I do this? It would be kind of like this.

RelativeLayout lay = new "myrelativelayout";
ImageView img = lay.children[0];
TextView txt = lay.children[1];

Thanks!


Solution

  • XML:

    <RelativeLayout
        android:id="@+id/relative_layout_id"
             ...>
        <TextView
            android:id="@+id/textview_id"
            .../>
    </RelativeLayout>
    

    Activity onCreate:

    RelativeLayout lay = (RelativeLayout) findViewById(R.id.relative_layout_id);
    

    To change children use:

    TextView child = (TextView) findViewById(R.id.textview_id);
    child.setText(text);
    

    or:

    View child = lay.getChildAt(i);