How to place Textviews in an array and findViewById?

I struggled with this problem for two days and still can not find a solution, I think that my basic knowledge of OOP is bad.

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

I tried using an array, for example:

 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 calls "name" and "allTextview [0]" does not point to the same object. I also use this solution , but still the same.

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

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

Thanks for the help, and please excuse my poor English.

+5
source share
1 answer

What you need to do is take another 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"); } } 
+3
source

All Articles