Android在循环中调用findViewById();

假设一个场景,如果开发一个类似计算器的应用,不说操作符,单是0~9十个数字就得连续写10次findViewById(),想想真是够了。那么,有没有简单点的方法呢?答案是肯定的。
我们知道,findViewById()方法传入的参数是int类型的,只要命名规则统一,就可以通过循环获取到。例如,10个Button的ID分别为:btn0~btn9,那么,我们直接定义一个 List<Button> btns = new ArrayList<Button>();
Resources res = getResources();
for (int i = 0; i < 9; i++) {
    int id = res.getIdentifier("btn" + i, "id", getPackageName());
    Button btn = (Button) findViewById(id);
    btns.add(btn);
}

这样,我们就取得了10个Button对象。注意,布局文件中的Button命名为:btn0~btn9。

查找资源~

try {
            R.mipmap d = new R.mipmap();
            for (int i = 1; i <= 28; i++) {
                Field fieldImgId = d.getClass().getDeclaredField("ic_fruit" + i);
                int imgId = (Integer) fieldImgId.get(d);//这个ID就是每个图片资源ID
                imageList.add(imgId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值