我希望片段有两个.xml
布局文件有条件我想在某个事件上启动一个并更改为其他,尝试搜索Javadoc以查找相关方法,任何指针都会有帮助
答案 0 :(得分:2)
您需要创建两个extends Fragment
类和override onCreateView()
方法的类,并使您的布局膨胀。例如:
Class FragmentOne.java
public class FragmentOne extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
//Inflate the layout for this fragment
return inflater.inflate(
R.layout.fragment_one, container, false);
}
}
Class FragmentTwo.java
public class FragmentTwo extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(
R.layout.fragment_two, container, false);
}
}
在 MainActivity.java
中 Fragment fr;
if(view == findViewById(R.id.button2)) {
fr = new FragmentTwo();
}else {
fr = new FragmentOne();
}
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_place, fr);
fragmentTransaction.commit();
答案 1 :(得分:0)
试试这个..
public class FragmentCont extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
//Inflate the layout for this fragment
if(condition1){
return inflater.inflate(
R.layout.fragment_one, container, false);
}else{
return inflater.inflate(
R.layout.fragment_two, container, false);
}
}
}