有没有办法使用变量更改参考路径



有没有办法使用变量更改对 Android 清单中 ID 的引用?

如:

for(int counter6=1;counter6 <= 12; counter6++)
                value = bundle.getString("value"+counter6);
                TextView text1 = (TextView) findViewById(R.id.textView+counter6);
                text1.setText(value);

是否可以在 ID 目录中使用 counter6 变量,以便 for 循环可以遍历所有不同的文本视图,分别使每个文本视图成为 text1,然后将其文本设置为字符串值?

如果它不能以这种方式工作,这不是真正的问题,它只是意味着要编写更多的代码行。

你不能真正在id上做一个循环,并在生成时递增它,但你可以创建一个引用数组,并通过获取该数组找到每个TextView并更新文本:

<array name="array_text_views">
       <item>@id/text_view_1</item>
       <item>@id/text_view_2</item>
       <item>@id/text_view_3</item>
<array>

在你的代码中,类似这样的东西:

ArrayList<TextView> myTextViews = new ArrayList<TextView>();
TypedArray ar = context.getResources().obtainTypedArray(R.array.array_text_views);
int len = ar.length();
for (int i = 0; i < len; i++){
    myTextViews.add(findById(ar[i]));
} 
ar.recycle(); 

我通常只会在代码的某个地方放一个小int[]的 Id 数组。如果有很多,请考虑以编程方式创建它们 ( layout.addView(new TextView(.. )。

例如,如果您想启动一个Activity并通过 Extras Bundle告诉它要显示哪些字符串,您可以直接将它们作为数组放置。

void startOther(String[] texts) {
    Intent i = new Intent( /* ... */);
    i.putExtra("texts", texts);
    // start via intent
}

现在在那个Activity里面,我会把ids作为一个"常量"。

// hardcoded array of R.ids
private static final int[] TEXT_IDS = {
    R.id.text1,
    R.id.text2,
    // ...
};

然后同时使用 bundle 和 id 数组,例如:

// a List of TextViews used within this Activity instance
private List<TextView> mTextViews = new ArrayList<TextView>(TEXT_IDS.length);
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.something);
    // find all TextViews & add them to the List
    for (int id : TEXT_IDS) {
        mTextViews.add((TextView)findViewById(id));
    }
    // set their values based on Bundle
    String[] stringArray = savedInstanceState.getStringArray("texts");
    for (int i = 0; i < mTextViews.size() && i < stringArray.length; i++) {
        mTextViews.get(i).setText(stringArray[i]);
    }
}

最新更新