Creating multiple buttons programmatically: Android

Viewed 3039

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 Answers
Related