Android复习笔记(13)-Fragment的使用(1)

fragment: 碎片,可以把屏幕划分成多个部分,单独显示一个界面。

fragment的使用(动态引用)
    1.定义activity_main布局文件,添加一个fragment的container
    2.定义fragment的布局文件,和变量activity文件一样。
    3.初始化Fragment组件,使用onCreateView初始化视图。
    4.MainActivity继承FragmentActivity,并添加fragment到activity中

例:、
Fragment1类
//在createView方法中创建fragment的视图
 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
   Bundle savedInstanceState) {
  //这里第二个参数传空,不然会报错
  return inflater.inflate(R.layout.frament1, null);
 }

//MainActivity类
lvMenu = (ListView) findViewById(R.id.lv_menu);
  String[] array = new String[] { "选项1", "选项2", "选项3", "选项4", "选项5",
    "选项6", "选项7", "选项8", "选项9", "选项10" };
  lvMenu.setAdapter(new ArrayAdapter<String>(this, R.layout.lv_item,
    R.id.tv_menu, array));

  lvMenu.setOnItemClickListener(new OnItemClickListener() {
   @Override
   public void onItemClick(AdapterView<?> parent, View view,
     int position, long id) {
    Object item = parent.getItemAtPosition(position);
    Toast.makeText(getApplicationContext(), item.toString(), 0).show();
    //获取FragmentManager
    FragmentManager fm = getSupportFragmentManager();
    //开启事务
    FragmentTransaction transaction = fm.beginTransaction();
    System.out.println(position);
    switch (position) {
    case 0:
     transaction.replace(R.id.ll_container, new Fragment1());
     break;
    case 1:
     transaction.replace(R.id.ll_container, new Fragment2());
     break;
    case 2:
     transaction.replace(R.id.ll_container, new Fragment3());
     break;
    default:
     transaction.replace(R.id.ll_container, new Fragment3());
     break;
    }
    transaction.commit();
   }
  });
 }

你可能感兴趣的:(android)