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?
-
Who says it is forbidden?– Shadab AnsariMar 18, 2016 at 0:57
-
@ShadabAnsari it was underlined with red, and the method itself has an annotation IdRes– Justin McGuireMar 18, 2016 at 1:08
-
@ShadabAnsari and when I did "setId(i)" in loop it threw NullPointerException for the previous Button though I checked the "previous" id starting with the second.– Justin McGuireMar 18, 2016 at 1:09
2 Answers
According to the API it's not forbidden or deprecated. Here is the best way of using it.
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>
once you have that, you can than use
setId
button1.setId(R.id.button1); button2.setId(R.id.button2);
-
when I tried "setId(1)" it was underlined with red. Thank you for your answer, gonna check it Mar 18, 2016 at 1:06
-
Yes, it's because the function definition is
public void setId(@IdRes int id)
which forces you to pass an ID resource. Glad it helped.– arsentMar 18, 2016 at 1:10 -
It's not NPE anymore. But I could't solve my main problem - they keep overlapping each other though I wrote "lp.addRule(RelativeLayout.ALIGN_TOP,buttons[i-1].getId());" and then set it to buttons... Mar 18, 2016 at 1:19
-
It's a different issue. You need to add another rule LeftOf or RightOf to the buttons. There is a solution here - stackoverflow.com/questions/10700273/…– arsentMar 18, 2016 at 1:22
-
Solved it! Many thanks! Just replaced "ALIGN_TOP" with "BELOW". And one more question (I know it's another topic too but maybe I be lucky): how to place programmatically-created RL at the bottom but outside the screen? ("rlp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM)" didn't help, it's placed top-left) Mar 18, 2016 at 1:32
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
-
-
-
So strange... it's not ok using int literals (underlines red) but works with int variables Mar 18, 2016 at 1:25