码迷,mamicode.com
首页 > 其他好文 > 详细

Fragment

时间:2015-01-17 00:59:38      阅读:466      评论:0      收藏:0      [点我收藏+]

标签:

概述:A Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a "sub activity" that you can reuse in different activities).

安卓3.0(api level11)开始引入的Fragment,可以把Fragment想成Activity中的模块,这个模块有自己的布局,有自己的生命周期,单独处理自己的输入,在Activity运行的时候加载或则移除

Fragment模块。

可以把Fragment设计成可以再多个Activity中复用的模块。

可以再应用程序中灵活的运用Fragment实现灵活的布局,改善用户体验

知识点一:

静态添加Fragment:

1、创建Fragment1.java文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
 * Fragment 是activity的一部分
 * @author Administrator
 *
 */
public class Fragment1 extends Fragment {
 
    /**
     * 类似 setcontetView() 方法   作用:显示Fragment 要显示 内容   
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // 我们可以利用 inflate  把 一个布局转换成一个view 对象
        View view = inflater.inflate(R.layout.fragment1, null);
        return view;
    }
     
     
}

2、同上

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
 * Fragment 是activity的一部分
 * @author Administrator
 *
 */
public class Fragment2 extends Fragment {
 
    /**
     * 类似 setcontetView() 方法   作用:显示Fragment 要显示 内容   
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // 我们可以利用 inflate  把 一个布局转换成一个view 对象
        View view = inflater.inflate(R.layout.fragment2, null);
        return view;
    }
     
     
}

3、自建xml文件fragment1和fragment2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
 
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="25sp"
        android:text="我是fragment1的内容" />
 
</LinearLayout>


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
 
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
         
        android:text="我是fragment2的内容" />
 
</LinearLayout>


注意在activity.xml文件中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    tools:context=".MainActivity" >
 
    <fragment
        android:id="@+id/fg1"
        android:name="com.itheima.fragmentdemo.Fragment1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />
 
    <fragment
          android:id="@+id/fg2"
        android:name="com.itheima.fragmentdemo.Fragment2"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />
 
</LinearLayout>

总结:以上是静态使用Fragnment的方法


动态使用Fragment:(案例:创建选项卡页面)

知识点:一下是主要代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
public class MainActivity extends Activity implements OnClickListener{
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btn_wx = (Button) findViewById(R.id.btn_wx);
        Button btn_contact = (Button) findViewById(R.id.btn_contact);
        Button btn_discover = (Button) findViewById(R.id.btn_discover);
        Button btn_mine = (Button) findViewById(R.id.btn_mine);
         
        //给按钮设置点击事件
         
        btn_wx.setOnClickListener(this);
        btn_contact.setOnClickListener(this);
        btn_discover.setOnClickListener(this);
        btn_mine.setOnClickListener(this);
         
         
    }
 
    @Override
    public void onClick(View v) {
         
        // 点击按钮动态加载 Fragment
        FragmentManager fragmentManager = getFragmentManager();  //拿到Fragment的管理者
        FragmentTransaction transaction = fragmentManager.beginTransaction();
         
         
        switch (v.getId()) {
        case R.id.btn_wx:   //点击微信tab
            transaction.replace(R.id.ll_layout, new WXFragment());
            break;
             
        case R.id.btn_contact:  //点击通讯录
            transaction.replace(R.id.ll_layout, new ContactFragment());
            break;
             
        case R.id.btn_discover:  //点击发现
            transaction.replace(R.id.ll_layout, new DiscoverFragment());
            break;
             
        case R.id.btn_mine:  //点击我
            transaction.replace(R.id.ll_layout, new MineFragment());
            break;
             
        }
         
        // 一定要记得 commit 
        transaction.commit();
         
         
         
    }
 
     
 
}




兼容低版本:注知识点就是用getSupportFragmentManager替代getFragmentManager来得到Fragmanager

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
 *
 * 想使用v4包中的Fragment  activity 必须继承  FragmentActivity
 * @author Administrator
 *
 */
public class MainActivity extends FragmentActivity{
 
    @SuppressWarnings("deprecation")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 获取手机的宽和高 
          
        WindowManager wm =  (WindowManager) getSystemService(WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();   //屏幕的宽度
        int height = wm.getDefaultDisplay().getHeight();
         
        // 判断是竖屏 还是 横屏    切换横竖屏 动态加载 Fragment
         
        //动态加载Fragment之前 要初始化 Fragmentmanager 
        FragmentManager supportFragmentManager = getSupportFragmentManager();  //获取到Fragment的管理者 (v4包)
         
        FragmentTransaction transaction = supportFragmentManager.beginTransaction();
         
        if (height > width) {
            // 属于竖屏
            //替换我想要的Fragment     android.R.id.content 理解成当前手机窗体
            transaction.replace(android.R.id.content, new Fragment1());
             
        }else {
            // 横屏
            transaction.replace(android.R.id.content, new Fragment2());
             
        }
         
        // 最后一步 一定要记得 commit
        transaction.commit();
         
         
         
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
 
}

Fragment之间通讯:各Fragement与同一Activity组件相关联

关键点:就是如何在Fragment1中得到Fragment2的对象

破解方法:在Fragement2中通过getActivity()得到该Fragment所关联的Activity然后用一下方法拿到Fragment2对象你懂得

1
2
//拿到的是mainActivity 
final Fragment2 fragment2 =  (Fragment2) getActivity().getFragmentManager().findFragmentByTag("fragment2");

实例:注意为fg1和fg2设置标记

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class MainActivity extends Activity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         
         
        // 动态的添加Fragment
         
        //1 拿到Fragment的管理器
        FragmentManager manager = getFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        /**
         * 第三个参数  tag   fragment的标示    可以利用tag  找到 我们关心的fragment
         */
        transaction.replace(R.id.ll1, new Fragment1(),"fragment1");
        transaction.replace(R.id.ll2, new Fragment2(),"fragment2");
         
        // 一定要记得 commit
        transaction.commit();
         
         
         
    }
 
     
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class Fragment1 extends Fragment {
    /**
     * fragment 要显示的内容
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
         
        View view = inflater.inflate(R.layout.fragment1, null);
        Button btn = (Button) view.findViewById(R.id.btn);
         
        //拿到的是mainActivity 
        final Fragment2 fragment2 =  (Fragment2) getActivity().getFragmentManager().findFragmentByTag("fragment2");
         
         
        // 要给按钮设置点击事件
        btn.setOnClickListener(new OnClickListener() {
             
            @Override
            public void onClick(View v) {
                 
                System.out.println("-------");
                 
                fragment2.setTextContent("哈哈");
                 
                 
            }
        });
         
         
        return view;
    }
     
 
}











Fragment

标签:

原文地址:http://www.cnblogs.com/candledragle/p/4229999.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!