简体   繁体   中英

How can we use a variable in R.id

The content of xml are

<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/MainFrame"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<AbsoluteLayout
    android:id="@+id/AbsoluteLayout1"
    android:layout_width="match_parent"
    android:layout_height="172dp"
    android:layout_x="12dp"
    android:layout_y="26dp"
    android:visibility="invisible" >

</AbsoluteLayout>

  <AbsoluteLayout
    android:id="@+id/AbsoluteLayout2"
    android:layout_width="match_parent"
    android:layout_height="172dp"
    android:layout_x="20dp"
    android:layout_y="184dp" android:visibility="invisible">

</AbsoluteLayout>

</AbsoluteLayout>

Here's the main code

String layoutid;
int ctr = 1;
AbsoluteLayout [] mainlayout = new AbsoluteLayout[12];

   while (ctr<3)
   {
        layoutid = "AbsoluteLayout" + ctr;
        mainlayout[ctr] = (AbsoluteLayout)findViewById(R.id.layoutid);
        ctr++;
   }

We need to make a loop to make

 ctr = 1 
 AbsoluteLayout + ctr = AbsoluteLayout1 
 ctr++; 

 AbsoluteLayout + ctr = AbsoluteLayout2

we want to declare the AbsoluteLayout1 and AbsouluteLayout2 but it doesn't work. We know that the R.id.layoutid is the culprit. So how can we resolve it?

I solved it using getIdentifier method

Button[] buttons; 
for(int i=0; i<buttons.length; i++) {
{
   String buttonID = "sound" + (i+1);

   int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
   buttons[i] = ((Button) findViewById(resID));
   buttons[i].setOnClickListener(this);
}

the id is an intiger value not string: hope u ll get an idea from below code

 while (ctr<3)
{
   int layoutid;
    if(ctr==1)
    { layoutid = R.id.AbsoluteLayout1;}
    else{
     layoutid = R.id.AbsoluteLayout2;}
    mainlayout[ctr] = (AbsoluteLayout)findViewById(layoutid);
    ctr++;
}
---------------------------------------------

all these won post an error as they are handled as int itself manipulate as you want you cant use this as it is as

int[] ctra={R.id.xx,R.id.xxx};
  int i=0;
 while (ctr<3)
{
mainlayout[i]=(AbsoluteLayout)findViewById(ctra[i]);
i++;}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM