My xml has a number of slots (TextViews) with ids like slot0 , slot1 ... slot15 .
Is there any way to access each of them using a for loop and generate the id dynamically to access it?
I am currently unable to use findViewById(R.id.customStringForId) as it cannot find it in the xml.
I was hoping to generate the corresponding Ids dynamically in java and access them. Can someone please help me out ?
CodePudding user response:
Thats a bad practice for access component from your xml
You need set manual for id with findViewById for tell java class if in your xml there existing textview with id which already you set and give you access for do whatever like implement onclick event, settext, etc.
If you cant find your id, you need check if setContentView in your java point to your xml.
CodePudding user response:
The first thing to know, the only way to access the XML Layout by the id is statically
but there are some ways to solve your problem but you should write your layout in the question to let us know how you design the layout.
But for example if you have a list of TextViews
inside layout like the following:
<LinearLayout
android:id="@ id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@ id/slot0"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="example" />
<TextView
android:id="@ id/slot1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="example" />
<TextView
android:id="@ id/slot2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="example" />
</LinearLayout>
you can access the TextView
Dynamically via the layout like the following:
public TextView getTextView(int index){
return ((LinearLayout) findViewById(R.id.layout)).getChildAt(index)
}