6

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 newbie in Fragment. I don't know whether it is a good way or not to add two Fragments to a Layout

Sorry. My English is not really well.

Aprian
  • 1,718
  • 1
  • 14
  • 24
kdtphdav
  • 225
  • 2
  • 4
  • 10
  • http://stackoverflow.com/questions/5159982/how-do-i-add-a-fragment-to-an-activity-with-a-programmatically-created-content-v – bigstones Sep 01 '12 at 02:53
  • thanks bigstones. After time tried. I decided to set fixing fragment layout width instead using layout_weight. But, any way, thank again – kdtphdav Sep 02 '12 at 17:22

2 Answers2

10
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT);
params.weight = 3.0f;
fragment.getView().setLayoutParams(params);
user457015
  • 960
  • 4
  • 14
  • 33
0

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:

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_a, container, false);
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT);
    params.weight = 1.0f;
    FragmentManager manager = getActivity().getFragmentManager();
    FragmentA fragmentA = (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:

public void addA(View v) {
        FragmentA fragmentA = new FragmentA();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.add(R.id.linearLayout, fragmentA, "A");
        transaction.commit();
}

Where linearLayout will be the parent for the fragments inside our activity layout.

Sergey Emeliyanov
  • 5,158
  • 6
  • 29
  • 52