两个XML元素具有相同的ID [英] Two XML elements with same id

查看:366
本文介绍了两个XML元素具有相同的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想修改两个TextViews在完全相同的方式。我想我可以给他们相同的ID,用findViewById()和的setText()方法改变这些TextViews两行。但似乎只有一个TextView的改变。

I'm trying to modify two TextViews in exactly the same way. I thought I can give them same id and with findViewById() and setText() methods change those TextViews in two lines. But it seems only one TextView is changed.

有没有办法做到这一点? 或者我必须做出不同的ID的每一个元素,通过findViewById获得每一个元素()方法,并设置它的文本?

Is there a way to do this? Or I have to make different ids for every element, get every element by findViewById() method and set it's text?

推荐答案

查看ID是纯整数,所以你可以简单地有要更改ID数组。例如:

View IDs are plain integers, so you can simply have an array of ids you want to change. For example:

int[] ids = { R.id.text1, R.id.text2, ... };
for (int id: ids) {
    TextView tv = (TextView) findViewById(id);
    tv.setText("Hello, World!");
}

当然,这将是最好有 IDS 为静态final类成员。即:

Of course, it would be best to have ids as a static final class member. I.e.:

public class MyActivity extends Activity {
    private static final int[] textViewIDs = {
        R.id.text1,
        R.id.text2,
        ...
    }
    ...
}

这篇关于两个XML元素具有相同的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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