如何将Textview放入数组并findViewById它们?

7

我已经苦恼了两天,仍然找不到解决方法,我认为我的面向对象编程基础知识很差。

现在我已经声明了大约二十个 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);
    }
}}

这种方法会导致"name"和"allTextView[0]"指向的不是同一个对象。我还尝试了这个解决方案,但问题仍然存在。

我认为原因是"name"和"address"只是被声明了,并没有指向任何对象,我该怎么解决呢?

我想使用for循环来findViewById,并且我可以同时使用"name"和"allTextView[0]"来对TextView进行操作。

谢谢您的帮助,请原谅我的英语水平不太好。


先尝试为姓名和地址分配ID... name.setId(int) - MKJParekh
你为什么想要像这样初始化一个TextView数组?做起来不是更简单/更有效率吗:int[] ids = new int[]{R.id.nameTextView,R.id.addressTextView},然后 for(int i=0;i<id.length;i++){allTextViews[i] = (TextView) findViewById(ids[i]);} - W.K.S
1个回答

7
你需要做的是使用不同的 String 数组来用于 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");
        }
    }

看起来这是实现我的目标最简单的方法,再次感谢。 - Aaron Tsai

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接