android - set ID to the view programmatically

对着背影说爱祢 提交于 2019-12-10 04:22:46

问题


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?


回答1:


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

  1. Create res/values/ids.xml and define

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
            <item type="id" name="button1" />
            <item type="id" name="button2" />
    </resources>
    
  2. once you have that, you can than use setId

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



回答2:


Since you said you can have any number of buttons then you can set id for each button using -

button.setId(View.generateViewId()); //Works for API 17 and above

If minSdk is below 17, then you can use -

 button.setId(counter++); //Each time counter will be increment giving a unique id


来源:https://stackoverflow.com/questions/36074297/android-set-id-to-the-view-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!