Programmatically Add Buttons To A Fragment
I've created a project with scrollable tabs. Each tab is declared by a fragment. And now i want f.e. Fragment1 to have 8 Buttons in it, Fragment2 4 Buttons and so on. I want to hav
Solution 1:
You can dynamically add buttons to ViewGroup
and inflate your view using it. Try the following code,
public class FragmentTobias extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
LinearLayout linearLayout = new LinearLayout(getActivity());
LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
linearLayout.setLayoutParams(layoutParams);
linearLayout.setOrientation(LinearLayout.HORIZONTAL); //or VERTICAL
LayoutParams buttonParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
Button button = new Button(getActivity());
button.setLayoutParams(buttonParams);
Button button2 = new Button(getActivity());
button2.setLayoutParams(buttonParams);
linearLayout.addView(button);
linearLayout.addView(button2);
//like this, add all buttons and other views
//you can use a loop for adding multiple similar views
container.addView(linearLayout);
View view = inflater.inflate(R.layout.tobias, container, false);
return view;
}
}
Post a Comment for "Programmatically Add Buttons To A Fragment"