如何将Textviews放入数组并findViewById呢?

Aar*_*sai 7 java arrays android

两天我一直在努力解决这个问题但仍然无法找到解决方案,我认为我对OOP的基本知识很差.

现在我宣布大约二十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);
    }
}}
Run Code Online (Sandbox Code Playgroud)

此方法导致"name"和"allTextview [0]"不指向同一对象.我也使用这个解决方案,但仍然是一样的.

我认为原因是"名称"和"地址"刚刚宣布,并没有指向任何对象,我该如何解决?

我想用循环来findViewById,我可以使用"name"和"allTextview [0]"来做某事TextView.

谢谢你的帮助,请原谅我可怜的英语.

mjo*_*osh 6

您要做的是使用另一个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>
Run Code Online (Sandbox Code Playgroud)

和活动文件

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");
        }
    }
Run Code Online (Sandbox Code Playgroud)