如何以编程方式将LayoutParams
设置为Fragment
?
实际上:我想以编程方式将两个Fragments
添加到一个LinearLayout
中,并且我需要为它们设置android:layout_weight
。我是Fragment
的新手。我不知道在一个Layout
上添加两个Fragments
是不是一个好方法
对不起。我的英语不是很好。
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT);
params.weight = 3.0f;
fragment.getView().setLayoutParams(params);
要在单亲LinearLayout中执行2个或多个片段的添加/替换/移除/附加/分离事务,我建议遵循以下基本步骤:
在Fragment类中,确保为片段指定LayoutParams,将layout_height(或水平方向的layout_width)设置为"0",同时将layout_weight设置为某个值:
@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);
}
在这里,我展示了单个Fragment(FragmentA)类的代码,但请确保在要使用的每个片段中都有类似的块。
现在,在"活动"中,您有LinearLayout,这里有一个在单个LinearLayout:中添加此类片段的示例
public void addA(View v) {
FragmentA fragmentA = new FragmentA();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(R.id.linearLayout, fragmentA, "A");
transaction.commit();
}
其中linearLayout将是我们活动布局中片段的父级。