Can I Set Layoutparams To Fragment By Programming
How can I set LayoutParams to Fragment programmatically? Actually : I wanna add two Fragments to a LinearLayout programmatically and I need set android:layout_weight for them. I am
Solution 1:
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT);
params.weight = 3.0f;
fragment.getView().setLayoutParams(params);
Solution 2:
To perform add/replace/remove/attach/detach transactions of 2 or more fragments inside a single parent LinearLayout I recommend to follow these basic steps:
Inside your Fragment classes, make sure you specify LayoutParams for your fragments setting the layout_height (or layout_width for horizontal orientation) to "0" while setting the layout_weight to some value:
@Overridepublic View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_a, container, false);
}
@OverridepublicvoidonActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
LinearLayout.LayoutParamsparams=newLinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT);
params.weight = 1.0f;
FragmentManagermanager= getActivity().getFragmentManager();
FragmentAfragmentA= (FragmentA) manager.findFragmentByTag("A");
fragmentA.getView().setLayoutParams(params);
}
Here I show the code for a single Fragment (FragmentA) class, but make sure you have similar blocks inside each fragment you're gonna use.
And now, inside the Activity, where you have your LinearLayout, here's an example of adding such fragments inside a single LinearLayout:
publicvoidaddA(View v) {
FragmentAfragmentA=newFragmentA();
FragmentTransactiontransaction= fragmentManager.beginTransaction();
transaction.add(R.id.linearLayout, fragmentA, "A");
transaction.commit();
}
Where linearLayout will be the parent for the fragments inside our activity layout.
Post a Comment for "Can I Set Layoutparams To Fragment By Programming"