我知道,Java没有预处理器,因此Java中有些东西或多或少是不可能的。

真的没有办法在循环中用动态名称填充这些数组吗?
我想要类似的东西:

for(int i=0;i<5;i++){
earnTvs[i]=(TextView) findViewById(R.id.INSERT_GREAT_TRICK_HERE("earn"+i+"Tv"));
}


代替

    earnTvs[0] = (TextView) findViewById(R.id.earn1Tv);
    earnTvs[1] = (TextView) findViewById(R.id.earn2Tv);
    earnTvs[2] = (TextView) findViewById(R.id.earn3Tv);
    earnTvs[3] = (TextView) findViewById(R.id.earn4Tv);
    earnTvs[4] = (TextView) findViewById(R.id.earn5Tv);
    timeTvs[0] = (TextView) findViewById(R.id.time1Tv);
    ...
    ownTvs[0] = (TextView) findViewById(R.id.own1Tv);
    ...
    costTvs[0] = (TextView) findViewById(R.id.build1Tv);
    ...
    buyBtns[0] = (ImageButton) findViewById(R.id.buy1Bt);
    ...
    progressBars[0] = (ProgressBar) findViewById(R.id.prog1pB);
    ...
    buildBtns[0] = (Button) findViewById(R.id.build1Bt);
    ...


还是有可以使用的古怪技巧?

最佳答案

我会那样做:

final int[] earnTvsId = new int[] {R.id.earn1Tv, R.id.earn2Tv, R.id.earn3Tv, R.id.earn4Tv ...};
for(int i = 0; i < earnTvsId.length; ++i){
    earnTvs[i] = (TextView) findViewById(earnTvsId[i]);
}


如果要使用getIdentifier()方法:

for (int i = 0; i < NUMBER_OF_TEXTVIEWS; ++i) {
    final int resId = getResources().getIdentifier("earn" + i + "Tv", "id", getPackageName());
    earnTvs[i] = (TextView) findViewById(resId);
}

07-24 09:23