Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
162 views
in Technique[技术] by (71.8m points)

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

question from:https://stackoverflow.com/questions/65623517/how-to-add-buttons-programmatically-in-android

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...