android - 以编程方式将ID设置为视图

Jus*_*ire 6 android view programmatically-created

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

ars*_*ent 12

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

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

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
            <item type="id" name="button1" />
            <item type="id" name="button2" />
    </resources>
    
    Run Code Online (Sandbox Code Playgroud)
  2. 一旦你有了,你可以使用 setId

    button1.setId(R.id.button1);
    button2.setId(R.id.button2);
    
    Run Code Online (Sandbox Code Playgroud)


Sha*_*ari 7

既然你说你可以有任意数量的按钮,那么你可以使用 - 设置每个按钮的id -

button.setId(View.generateViewId()); //Works for API 17 and above
Run Code Online (Sandbox Code Playgroud)

如果minSdk低于17,那么你可以使用 -

 button.setId(counter++); //Each time counter will be increment giving a unique id
Run Code Online (Sandbox Code Playgroud)