如何以编程方式添加和删除Fragment中的视图

时间:2014-10-04 03:18:37

标签: java android layout view fragment

我希望片段有两个.xml布局文件有条件我想在某个事件上启动一个并更改为其他,尝试搜索Javadoc以查找相关方法,任何指针都会有帮助

2 个答案:

答案 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);
   }


  }
}