Java 如何将TextView放入数组并查找它们?
我已经为这个问题挣扎了两天,仍然找不到解决方案,我认为我的OOP基础知识很差 现在我已经声明了大约二十个Java 如何将TextView放入数组并查找它们?,java,android,arrays,Java,Android,Arrays,我已经为这个问题挣扎了两天,仍然找不到解决方案,我认为我的OOP基础知识很差 现在我已经声明了大约二十个TextView,我想知道是否有一种方法可以将TextView存储到一个数组中,并findViewById它们 我尝试使用数组,如下所示: public class MainActivity extends Activity { private TextView name, address; LinkedHashMap<Integer, TextView> demo = new
TextView
,我想知道是否有一种方法可以将TextView
存储到一个数组中,并findViewById
它们
我尝试使用数组,如下所示:
public class MainActivity extends Activity {
private TextView name, address;
LinkedHashMap<Integer, TextView> demo = new LinkedHashMap<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int temp;
allTextview = new TextView[]{name, address};
for(int i=0; i<allTextview.length; i++){
temp = getResources().getIdentifier(allTextview[i], "id", getPackageName());
allTextview[i] = (TextView)findViewById(temp);
}
}}
公共类MainActivity扩展活动{
私有文本视图名称、地址;
LinkedHashMap demo=新建LinkedHashMap();
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
内部温度;
allTextview=新的TextView[]{name,address};
对于(int i=0;i,但仍然相同)
我想原因是“姓名”和“地址”刚刚声明,还没有指向任何对象,我该如何解决
我想使用for循环来findViewById
,我可以使用“name”和“allTextview[0]”来处理TextView
谢谢您的帮助,请原谅我的英语不好。您需要做的是使用一个不同的字符串
数组将其用于getIdentifier
这是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="vertical" >
<TextView
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Name"/>
<TextView
android:id="@+id/address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Address"/>
</LinearLayout>
和Activity文件
public class TestActivity extends Activity{
private String[] id;
private TextView[] textViews = new TextView[2];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.testactivity);
int temp;
id = new String[]{"name", "address"};
for(int i=0; i<id.length; i++){
temp = getResources().getIdentifier(id[i], "id", getPackageName());
textViews[i] = (TextView)findViewById(temp);
textViews[i].setText("Text Changed");
}
}
公共类测试活动扩展活动{
私有字符串[]id;
私有文本视图[]文本视图=新文本视图[2];
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.testactivity);
内部温度;
id=新字符串[]{“名称”,“地址”};
对于(int i=0;我必须尝试将id分配给name,address first…name.setId(int)
为什么要这样初始化一个文本视图数组?这样做会不会更简单/更有效:int[]id=new int[]{R.id.nameTextView,R.id.addressextview}
然后对(inti=0;我想这是实现我目标的最简单的方法,再次感谢。