android,我怎么能用For循环使这段代码变短

时间:2014-03-09 09:21:30

标签: android

这是我的代码

LinearLayout ll[] = new LinearLayout [9];
ll[0]=(LinearLayout)findViewById(R.id.rlay1);
ll[1]=(LinearLayout)findViewById(R.id.rlay2);
ll[2]=(LinearLayout)findViewById(R.id.rlay3);
ll[3]=(LinearLayout)findViewById(R.id.rlay4);
ll[4]=(LinearLayout)findViewById(R.id.rlay5);
ll[5]=(LinearLayout)findViewById(R.id.rlay6);
ll[6]=(LinearLayout)findViewById(R.id.rlay7);
ll[7]=(LinearLayout)findViewById(R.id.rlay8);
ll[8]=(LinearLayout)findViewById(R.id.rlay9);
ll[9]=(LinearLayout)findViewById(R.id.rlay10);

3 个答案:

答案 0 :(得分:2)

您可以将ID放入数组中:

int[] ids = new int[] {R.id.rlay1, R.id.rlay2, R.id.rlay3, R.id.rlay4, R.id.rlay5,
     R.id.rlay6, R.id.rlay7, R.id.rlay8, R.id.rlay9, R.id.rlay10};
LinearLayout ll[] = new LinearLayout [10];
for (int i = 0; i < 10; i++) {
    ll[i] = (LinearLayout)findViewById(ids[i]);
}

我比使用Resources.getIdentifier更喜欢这个解决方案,因为它不会在运行时导致资源ID查找成本。

答案 1 :(得分:1)

将此方法添加到您的代码中:

protected final static int getResourceID
(final String resName, final String resType, final Context ctx)
{
    final int ResourceID =
        ctx.getResources().getIdentifier(resName, resType,
            ctx.getApplicationInfo().packageName);
    if (ResourceID == 0)
    {
        throw new IllegalArgumentException
        (
            "No resource string found with name " + resName
        );
    }
    else
    {
        return ResourceID;
    }
}

然后更改您的代码:

LinearLayout ll[] = new LinearLayout [10];
Context ctx = getApplicationContext();
for (int i = 0; i < 10; i++)
{
    ll[i] = (LinearLayout) findViewById(getResourceID("rlay" + (i + 1), "id", ctx));
}

答案 2 :(得分:1)

LinearLayout ll[] = new LinearLayout [10];
int counter = 0;
for (int i = 1; i < 11; i++) {
  int id = getResources().getIdentifier("rlay"+i, "id", getPackageName());
  ll[counter++] =  (LinearLayout)findViewById(id);
}