android - 以编程方式将 ID 设置为视图 [英] android - set ID to the view programmatically

查看:44
本文介绍了android - 以编程方式将 ID 设置为视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以编程方式添加按钮按钮的数量取决于某些条件.要为 RelativeLayout.LayoutParams 添加规则,使 按钮 对齐到彼此的顶部,我需要设置它们的 ID.2-3 年前的所有答案都说 setId(int) 没问题(例如 setId(1))但现在被禁止了(UPD. 仅使用 int 文字是不行的.使用 int 变量一切正常.想知道为什么).现在怎么做?

I'm adding Buttons programmatically and the number of Buttons depends on some conditions. To add rules for RelativeLayout.LayoutParams that Buttons be aligned to the top of each other I need to set their IDs. All the answers from 2-3 years ago say that setId(int) is okay (e.g. setId(1)) but now it's forbidden (UPD. it's not ok only with int literals. With int variables everything is ok. Wonder why). How to do it nowadays?

推荐答案

根据API 没有被禁止或弃用.这是使用它的最佳方式.

According to the API it's not forbidden or deprecated. Here is the best way of using it.

  1. 创建res/values/ids.xml并定义

<?xml version="1.0" encoding="utf-8"?>
<resources>
        <item type="id" name="button1" />
        <item type="id" name="button2" />
</resources>

  • 一旦你有了它,你就可以使用 setId

    button1.setId(R.id.button1);
    button2.setId(R.id.button2);
    

  • 这篇关于android - 以编程方式将 ID 设置为视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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