Accessing Android Views in Java files

662 views Asked by At

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!

2

There are 2 answers

1
Anton Kovalyov On BEST ANSWER

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);
0
Anindya Dutta On

To access the layout we use the findViewById method. Therefore to change the image in the ImageView you do not really need access to the RelativeLayout.

The way we access any element through its id is as follows:

View v = (View)findViewById(R.id.view_id);

where view_id is the ID of the view.

To access the RelativeLayout, therefore, the piece of code would be:

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

But if you only want to change the text in the TextView, you really don't need the above code. It is sufficient if you do a similar access for the TextView:

TextView textView = (TextView) findViewById(R.id.id_of_textview);
textView.setText(text);

A general method of accessing any resource can be found here.