Creating Multiple Buttons Programmatically: Android
Solution 1:
First of all, you should use LinearLayout
with HORIZONTAL
orientation, istead of RelativeLayout
, because in Relative
all your views will be in the same place (that's why you can see only one Button
)
Solution 2:
First, you create single Button btnTag
, then you loop and change this single button multiple times (so it makes no sense as all changes but last ones are overwritten). Finally, you add that single button to the view group. Once. So all here works correctly (except this is not what you expected).
You should make button creation and addView()
part of your loop.
Button btnTag;
for (int j = 0; j < 4; j++) {
btnTag = (Button) inflater.inflate(R.layout.buttons, null,
false);
...
btnTag.setId(j);
townLayout.addView(btnTag);
}
Also, as you use own XML file for button inflation, you should move certain attributes to that XML and then remove all setClickable()
, setTextColor()
etc.
You should consider replacing RelativeLayout
container with i.e. vertical LinearLayout, otherwise you will end up with buttons overlapping each other (as your code does not position them).
Post a Comment for "Creating Multiple Buttons Programmatically: Android"