Creating multiple buttons programmatically: Androi

2019-07-10 05:15发布

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,

and many other, but I can't make multiple buttons here. Only a single button is being displayed everytime. Can anyone please help?

2条回答
疯言疯语
2楼-- · 2019-07-10 06:04

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)

查看更多
干净又极端
3楼-- · 2019-07-10 06:12

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).

查看更多
登录 后发表回答