问题
I know that this has been asked several times before but I can't get a solution to mine issue. I am trying to add multiple buttons programmatically. I want the buttons to be aligned horizontally. However, only one button is showing up. What I have tried so far is,
private void locationSort() {
RelativeLayout townLayout = (RelativeLayout) locationLayout.findViewById(R.id.town_sort);
for (int i = 0; i <= 3; i++) {
LayoutInflater inflater = getLayoutInflater();
Button btnTag = (Button) inflater.inflate(R.layout.buttons, null,
false);
for (int j = 0; j < 4; j++) {
btnTag.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
btnTag.setText("Button");
btnTag.setBackgroundResource(R.drawable.alpha_button_selector);
btnTag.setClickable(true);
btnTag.setTextColor(Color.WHITE);
btnTag.setGravity(Gravity.CENTER);
btnTag.setId(j);
}
townLayout.addView(btnTag);
btnTag.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(context, "this is test", Toast.LENGTH_SHORT).show();
}
});
}
}
I have searched on the same and gone through the links like,
- Android: programmatically adding buttons to a layout
- Android - How to add several buttons with different layout_margins in a LinearLayout programmatically?
- android add multiple buttons on fly
and many other, but I can't make multiple buttons here. Only a single button is being displayed everytime. Can anyone please help?
回答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
)
回答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).
来源:https://stackoverflow.com/questions/45478444/creating-multiple-buttons-programmatically-android