我们如何使用R.id变量 [英] How can we use a variable in R.id

查看:702
本文介绍了我们如何使用R.id变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

XML的含量

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

下面是最主要的code

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

我们想声明的AbsoluteLayout1和AbsouluteLayout2,但它不工作。我们知道,R.id.layoutid是罪魁祸首。那么,如何才能解决这个问题?

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?

推荐答案

我解决它使用则getIdentifier方法

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

这篇关于我们如何使用R.id变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆