Search code examples
androidandroid-studiotabstextviewfindviewbyid

Read Tab content in Android Studio


In my java code in Android Studio, I have a simple tab structure with below structure:

<TabHost
    android:id="@android:id/tabhost"
    ....>
    <LinearLayout
        ....>
        <TabWidget
            android:id="@android:id/tabs"
            ....>
            <TextView
                ...
                android:text="tab0" />
            <TextView
                ...
                android:text="tab1" />
        </TabWidget>
        <FrameLayout
            android:id="@android:id/tabcontent"
            ...>
            <TextView
                android:id="@+id/textView_0"
                android:text="content0"
                ..../>
            <TextView
                android:id="@+id/textView_1"
                android:text="content1"                 
                ..../>
        </FrameLayout>
    </LinearLayout>
 </TabHost>

In one part of my code, I need to read the TextVeiw contents. While I can read the tab titles with below code, but I could not find a way to access the tab's content ( I can see the content on mobile's screen

...
TabWidget tab_widgets = tabHost.getTabWidget();
FrameLayout tab_contents = tabHost.getTabContentView();

for (int index = 0; index < tab_widgets.getChildCount(); index++) {

  //access tab's title: Works OK !!
  View v_title = 
    tab_widgets.getChildAt(index).findViewById(android.R.id.title);
  TextView tv_title = (TextView) v_title;

  //access tab's content: NOT working ??
  View v_content = 
    tab_contents.getChildAt(index).findViewById(android.R.id.title);
  TextView tv_content = (TextView) v_content; // It is always NULL
}

Is there any idea about this? how can I read the text inside tabs' body?


Solution

  • the line tab_contents.getChildAt(index).findViewById(android.R.id.title); needs some changes:

    A. use your custom id, in this case textView_0 or textView_1 make sure you use R.id. and not the android.R.id

    B. use either getChildAt() or findViewById(), not both

    like: tab_contents.getChildAt(index) or tab_contents.findViewById()