Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put Textviews in an array and findViewById them?

I've been struggling with this problem two days and still can't find a solution, I think my basic knowledge of OOP is poor.

Now I have declared about twenty TextView, and I want to know is there a way to store TextView into an array, and findViewById them?

I tried to use an array, like this:

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);
    }
}}

This method cause "name" and "allTextview[0]" not point to the same object. I also use this solution, but still the same.

I think the reason is "name" and "address" were just declared, and not point to any object yet, how can I solve it?

I want use for loop to findViewById, and I can use both "name" and "allTextview[0]" to do something with TextView.

Thanks for helping, and please excuse my poor English.

like image 206
Aaron Tsai Avatar asked Jul 25 '15 05:07

Aaron Tsai


1 Answers

What you have to do is take a different String array to use it for getIdentifier.

Here is the 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>

And the Actvity File

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");
        }
    }
like image 96
mihirjoshi Avatar answered Oct 19 '22 20:10

mihirjoshi