Search code examples
androidtextviewandroid-relativelayoutsettext

Set a TextView text without id under a relativeLayout with id


Is it possible to access a textview without id under a relativlayout with id to change its text?

Here an example code:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/backFace"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    >
<TextView
    android:gravity="center_horizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Back"
    />
 </RelativeLayout>

Solution

  • In order to manipulate a view , you need to get a reference to it, which is done by findViewById method. Therefore, if you're not providing any IDs for a specific view, then you won't have a reference, regardless of the hierarchy of your layout.

    But surprisingly, there's one workaround for this scenario.since RelativeLayout extends ViewGroup which has the getChildCount() and getChildAt(int index) methods, you can try this:

       TextView tv_child= (TextView)relativeLayout.getChildAt(i); // i = index of the textview