在 CardView
中,我有一个 LinearLayout
,其中包含三个 TextView
,我想从这些 TextView 中获取文本。我的 XML 文件如下所示:
<LinearLayout
android:id="@+id/defense"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal"
>
<android.support.v7.widget.CardView
android:id="@+id/cardCB"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_weight="1"
app:cardBackgroundColor="@android:color/transparent"
app:cardElevation="0dp">
<LinearLayout
android:id="@+id/innerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Rannochia"
android:textAlignment="center"
android:textStyle="bold"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="78"
android:textAlignment="center"
android:textStyle="bold"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="CB"
android:textAlignment="center"
android:textStyle="bold"/>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
然后我想迭代父 LinearLayout 中的所有 CardView 并获取 TextView。像这样的事情:
for (int i = 0; i < defense.getChildCount(); i++){
String getName = ((CardView)defense.getChildAt(i)).getText().toString();
id[i] = getName;
}
但我无法像这样调用方法 getText().toString();
。如何从 CardView 内的这些 TextView 获取文本?
最佳答案
这里有很多选择。
1.为您的 TextView 提供 id
2.在带有 id innerLayout
的 LinearLayout 中使用 for
3.当你的 UI 是动态的并且你需要从防御中获取 TextViews
for (int i = 0; i < defense.getChildCount(); i++){
CardView card = defense.getChildAt(i);
ViewGroup viewGroup = ((ViewGroup)card.getChildAt(0));
for(int j=0;j<viewGroup.getChildCount();j++){
String getName = ((TextView)viewGroup.getChildAt(j)).getText().toString();
id[i] = getName;
}
}
关于java - 如何从 CardView 内的 TextView 获取文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45543306/