如何设置LayoutParams
到Fragment
以编程方式?我可以通过编程将LayoutParams设置为片段
其实我想添加两个Fragments
到LinearLayout
编程,我需要设置android:layout_weight
他们。我是Fragment
的新手。我不知道这是不是一个好方法,或者不加Fragments
到Layout
对不起。我的英语不太好。
如何设置LayoutParams
到Fragment
以编程方式?我可以通过编程将LayoutParams设置为片段
其实我想添加两个Fragments
到LinearLayout
编程,我需要设置android:layout_weight
他们。我是Fragment
的新手。我不知道这是不是一个好方法,或者不加Fragments
到Layout
对不起。我的英语不太好。
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT);
params.weight = 3.0f;
fragment.getView().setLayoutParams(params);
要进行添加/替换/删除/安装/拆卸一个单亲的LinearLayout我建议遵循以下基本步骤中的2个或多个片段的交易:
您的片段类中,请确保您指定的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);
}
在这里,我展示了一个片段的代码(FragmentA)类,但要确保你有simi在你要使用的每个片段里面放上一些块。
而现在,活动,你有你的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将是我们的活动布局内的片段父。
http://stackoverflow.com/questions/5159982/how-do-i-add-a-fragment-to-an-activity-with-a-programmatically-created-content-v – bigstones
感谢bigstones。经过时间的努力。我决定使用layout_weight设置固定片段布局宽度。但是,无论如何,再次感谢 – kdtphdav