Search code examples
androidbuttonandroid-relativelayout

how to add buttons programmatically in android


I want something like this in my activity layout:

enter image description here

If user click +Add Other then it should add a button programmatically. I have used relative layout but it's not working.

Here is the code that I tried:

View root;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        root = inflater.inflate(R.layout.fragment_pay_remind_fragment, container, false);

        Button b = new Button(getContext());
        Button b1 = new Button(getContext());
        Button b2 = new Button(getContext());
        Button b3 = new Button(getContext());
        Button b4 = new Button(getContext());


        RelativeLayout.LayoutParams rl = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);;
        b.setLayoutParams(rl);

        RelativeLayout layout = (RelativeLayout) root.findViewById(R.id.relativeLayout);
        layout.addView(b);
        layout.addView(b1);
        layout.addView(b2);
        layout.addView(b3);
        layout.addView(b4);


        return root;
    }

Results are like this, which I don't want.

enter image description here


Solution

  • For your case i want to suggest you to use Flow from constraintLayout instead of RelativeLayout. You can learn more by reading this article.