Skip to content Skip to sidebar Skip to footer

Adding Buttons To Fragments Dynamically

I have been trying to add buttons to my fragment dynamically but all the methods I have tried somehow doesnt work. These are some methods I have tried: 1. public View onCreateView(

Solution 1:

The onCreateView method expects you to return the view which you are inflating. Your code is good, but you're adding the buttons to the wrong view. Try this instead:

//container.addView(linearlayout);
myView = inflater.inflate(R.layout.fragment_general_layout, container, false);
myView.addView(linearlayout);

This should add your buttons to your view. I'm assuming that your R.layout.fragment_general_layout is a LinearLayout with orientation="vertical"

Solution 2:

In the end, I have manged to do it. The second method had problem as there is no

btn = myView.findViewById(id_);. This will be pointing to null although I have set my button's ID to be the value I stated. Using this method, it is easy to still get the value of the button by setting a separate onClick() method.

for (inti=0; i < ArrayOfNames.length; i++) {

                finalButtonmyButton=newButton(myView.getContext());
                myButton.setText(RAnames[i]);
                myButton.setId(i + 1);
                myButton.setOnClickListener(this);

                myButton.setBackgroundColor(getResources().getColor(R.color.colorAccent));
                myButton.setTextSize(18);
                myButton.setPadding(20, 0, 20, 0);

                LinearLayoutlinearlayout= (LinearLayout) myView.findViewById(R.id.btnholder);
                linearlayout.setOrientation(LinearLayout.VERTICAL);

                LinearLayout.LayoutParamsbuttonParams=newLinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT);
                buttonParams.setMargins(0, 0, 0, 10);

                linearlayout.addView(myButton, buttonParams);
}

Post a Comment for "Adding Buttons To Fragments Dynamically"