我想制作一个TextView的ArryList。
扇区.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:gravity="center">
<TextView
android:id="@+id/sectNameVew"
android:layout_width="0sp"
android:layout_height="wrap_content"
android:layout_weight="60"
android:textSize="20sp"/>
</LinearLayout>
现在我想创建一个像这样的ArrayList:
ArrayList<TextView> arLst = new ArrayList<>();
for(int i = 0; i < 10; i++){
TextView tv = findViewById(R.id.sectorNamesView);
tv.setText((i + 1) + "");
arrLst.add(tv);
}
当我使用arLst时,它显示arrLst中的每个TextView都有文本“10”。 但我想存储它,因为每个 TextView 将有不同的文本,如“1”、“2”、“3”、……“10”。 即使我想在用户的 arrLst 中动态添加更多项目。所以不能在xml文本中定义10个TextView。因为项目数量可能会增加。
我怎样才能做到这一点? 谢谢<3
最佳答案
您希望以编程方式创建 TextView
并将其添加到 LinearLayout
(父 View )。
首先,您需要为您的LinearLayout
分配一个id
:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/parentLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:gravity="center">
</LinearLayout>
所以,你的代码看起来有点像这样:
LinearLayout parentLayout = (LinearLayout) findViewById(R.id.parentLayout);
int num_textViews = 10; // number of textViews you might want in your ArrayList
ArrayList<TextView> arrayList = new ArrayList<>();
for (int i = 0; i < num_textViews; i++) {
TextView tv = new TextView(this);
tv.setText((i + 1) + "");
// add any styling you wish
arrayList.add(tv);
parentLayout.addView(tv);
}
关于java - 有没有办法从 xml 中定义的一个 TextView 制作一个 TextView 的 ArrayList ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59921274/