Fragment学习

来源:互联网 发布:电脑看淘宝直播 编辑:程序博客网 时间:2024/06/05 19:10

Fragment学习


    Fragment可以看作是一种轻量级的Activity,它像Activity一样具有生命周期,也可以有自己的布局和输入事件,但是它比Activity更加灵活。Fragment的目的是适配不同终端屏幕分辨率,确保软件在不同终端上都有良好的用户体验。    本文实现了Fragment的基本使用和动态切换。    1.定义Fragment类(extends Fragment)和对应的布局文件,将Fragment对应的view绑定上(如果有的话)。这里app.Fragment和v4.app.Fragment好像在效果上没啥区别,由于我更在意基本的使用,也没细看文档里的差别。    2.在主函数中定义点击事件用来动态切换fragment。    代码如下:    1.三个Fragment,AboveFragment生成上方Fragment,BelowFragment生成下方Fragment,SecondAboveFragment是点击事件发生时切换到新的Fragment。
package com.bupt.markfavor.demo0916fragment;import android.os.Bundle;import android.support.annotation.Nullable;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;/** * Created by markfavor on 2017/9/16. */public class AboveFragment extends Fragment{    public static AboveFragment instance = new AboveFragment();    public static AboveFragment getInstance(){        return instance;    }    private TextView myTextView;    @Nullable    @Override    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {        View view = inflater.inflate(R.layout.layout_above,container,false);        myTextView = (TextView) view.findViewById(R.id.tv1);        return view;    }}
package com.bupt.markfavor.demo0916fragment;import android.support.v4.app.Fragment;import android.os.Bundle;import android.support.annotation.Nullable;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;/** * Created by markfavor on 2017/9/16. */public class BelowFragment extends Fragment {    private TextView myTextView;    public  static  BelowFragment instance=new BelowFragment();    public  static  BelowFragment getInstance(){        return instance;    }    @Nullable    @Override    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {        View view = inflater.inflate(R.layout.layout_below,container,false);        myTextView = (TextView) view.findViewById(R.id.tv2);        return view;    }}
package com.bupt.markfavor.demo0916fragment;import android.os.Bundle;import android.support.annotation.Nullable;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;/** * Created by markfavor on 2017/9/16. */public class SecondAboveFragment extends Fragment {    private TextView textView;    public  static  SecondAboveFragment instance=new SecondAboveFragment();    public  static  SecondAboveFragment getInstance(){        return instance;    }    @Nullable    @Override    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {        View view = inflater.inflate(R.layout.layout_second_above,container,false);        textView = (TextView) view.findViewById(R.id.tv3);        return view;    }}

对应的三个布局:依次为above,below,second_above

<?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:background="#fcfbfb"    android:orientation="vertical">    <TextView        android:id="@+id/tv1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center_horizontal"        android:text="This is above fragment"        android:textSize="30sp" /></LinearLayout>
<?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:background="#000000"    android:orientation="vertical">    <TextView        android:id="@+id/tv2"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center_horizontal"        android:text="This is below fragment"        android:textColor="#ffffff"        android:textSize="30sp" /></LinearLayout>
<?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/tv3"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center_horizontal"        android:text="This is second above fragment"        android:textSize="30sp" /></LinearLayout>

上边的代码定义了三个Fragment并且都给他们inflate了布局文件,布局文件里均只有一个textview,里面的文本标识了这是哪个fragment的布局。
下面是MainActivity的代码和布局文件:

package com.bupt.markfavor.demo0916fragment;import android.os.Bundle;import android.support.v4.app.FragmentManager;import android.support.v4.app.FragmentTransaction;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.Button;public class MainActivity extends AppCompatActivity {    private Button myButton,myButton2;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        myButton = (Button) findViewById(R.id.btn1);        myButton2 = (Button) findViewById(R.id.btn2);        setlistener();    }    @Override    protected void onResume() {        super.onResume();        FragmentManager fragmentManager=getSupportFragmentManager();        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();        fragmentTransaction.replace(R.id.above,AboveFragment.getInstance());        fragmentTransaction.addToBackStack(null);//在后台堆栈中保存相应状态        fragmentTransaction.commit();    }    private void setlistener() {        myButton.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                FragmentManager fragmentManager=getSupportFragmentManager();                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();                fragmentTransaction.replace(R.id.above,AboveFragment.getInstance());                fragmentTransaction.addToBackStack(null);//在后台堆栈中保存相应状态                fragmentTransaction.commit();            }        });        myButton2.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                FragmentManager fragmentManager=getSupportFragmentManager();                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();                fragmentTransaction.replace(R.id.above,SecondAboveFragment.getInstance());//                fragmentTransaction.addToBackStack(null);//在后台堆栈中保存相应状态                fragmentTransaction.commit();            }        });    }}
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context="com.bupt.markfavor.demo0916fragment.MainActivity">    <Button        android:id="@+id/btn1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="EXCHANGE FRAGMENT"        android:textSize="20sp" />    <Button        android:id="@+id/btn2"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="EXCHANGE FRAGMENT2"        android:textSize="20sp" />   <!-- <fragment        android:id="@+id/above"        android:name="com.bupt.markfavor.demo0916fragment.AboveFragment"        android:layout_width="match_parent"        android:layout_height="0dp"        android:layout_weight="1" />-->    <FrameLayout        android:id="@+id/above"        android:layout_width="match_parent"        android:layout_height="0dp"        android:layout_weight="1" />    <fragment        android:id="@+id/below"        android:name="com.bupt.markfavor.demo0916fragment.BelowFragment"        android:layout_width="match_parent"        android:layout_height="0dp"        android:layout_weight="1" /></LinearLayout>
这个布局文件当中定义了两个按钮,用来实现两个above的fragment的动态切换,下边定义了一个帧布局,用来占据上方的位置。下方是一个fragment,直接将android:name属性指定为belowfragment。为什么上下不一样呢?本来上方我也是通过指定android:name来写的,但发现这样写的话在触发点击事件时,原来的fragment不会被替换。而用framelayout占据这个位置,随后在用.replace()替换它是完全可行的。MainActivity当中,绑定了按钮,并且设定了监听器。在onResume当中替换framelayout为AboveFragment。这里比较容易理解:就是通过新建一个manager,通过begintransaction方法来开始动作,最后以commit结尾。需要说明的是,getinstance()这个方法是我为了方便使用,写在fragment里的一个方法,功能就是获取一个对应fragment的实体。最后效果图:![启动图](http://img.blog.csdn.net/20170916204904981?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbWFya2Zhdm9y/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)![按下第二个按钮后的图](http://img.blog.csdn.net/20170916204957830?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbWFya2Zhdm9y/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)再按第一个按钮又会回到第一张图的样子。就是这样。