-1

In my XML layout I have some TextView with ids like slot0, slot1...slot15.
Is there any way to generate the corresponding Id dynamically in java like the following?
findViewById(R.id.*customStringForId*)
then access each of TextView using a for loop?

I am currently unable to use findViewById(R.id.*customStringForId*) because I can't find it in the XML.

Auspex
  • 2,175
  • 15
  • 35
Jeronimo
  • 11
  • 2

2 Answers2

1

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.

Rifaldi
  • 67
  • 6
0

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

Aiman Alyosofi
  • 625
  • 1
  • 13