【问题标题】:Read Tab content in Android Studio在 Android Studio 中读取 Tab 内容
【发布时间】:2018-11-04 20:19:34
【问题描述】:

在我在 Android Studio 中的 java 代码中,我有一个简单的选项卡结构,其结构如下:

<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>

在我的代码的一部分中,我需要阅读 TextVeiw 内容。 虽然我可以使用以下代码阅读标签标题,但我找不到访问标签内容的方法(我可以在手机屏幕上看到内容

...
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
}

对此有什么想法吗?如何阅读标签正文中的文本?

【问题讨论】:

  • 显然,TextViews 可以使用它们的显式 id 直接访问。但是在这里,我想在循环中访问它们,例如“对于所有 TextViews ...做...”

标签: android android-studio tabs textview findviewbyid


【解决方案1】:

tab_contents.getChildAt(index).findViewById(android.R.id.title); 行需要修改:

A.使用您的自定义id,在本例中为textView_0 或textView_1 确保你使用R.id. 而不是android.R.id

B.使用 getChildAt() 或 findViewById(),不能同时使用

点赞:tab_contents.getChildAt(index) 或 tab_contents.findViewById()

【讨论】:

  • tab_contents.getChildAt(index),没有 findViewById 工作!谢谢!但我想知道为什么 tab_widgets 需要 findViewById 。我单独测试了 tab_widgets.getChildAt(index) ,但它不起作用。你知道为什么吗?
  • @hamzee TabWidget 在得到一个孩子时返回一个 Linearlayout 作为回报。将其转换为ViewGroup,然后您会在其中找到您的Textview。
猜你喜欢
  • 1970-01-01
  • 2017-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-06
  • 1970-01-01
  • 1970-01-01
  • 2012-02-25
相关资源
最近更新 更多