Android Fragment的使用

一,*Fragment的簡介:*
1、Fragment是android3.0引入的心的API,它代表Activity的子模板,所以可以把fragment理解爲Activity片段。
2、Fragment必須被“嵌入”Avtivity中使用,因此Fragment也擁有自己的生命週期,不過Fragment的生命週期受Activity所控制,也就是說Activity停止的時候,Activity中所有的Fragment都會被停止。其他狀態也是一樣。


二,Fragment的靜態加載
首先要創建一個Fragment,然後在創建一個Activity使其讓Fragment能夠在Activity上寄存起來,然後在Activity的佈局文件中添加fragment的節點

<fragment
    android:id="@+id/fragment_show"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:name="com.example.dfcn.sexmouth.Fragment.OneFragment">//fragment的顯示界面</fragment>

注意在fragment節點內一定得要添加id,否則程序在編譯的時候會報錯!


三,Fragment的動態加載
實現流程:
這裏寫圖片描述

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Display dis = getWindowManager().getDefaultDisplay();
        if(dis.getWidth() > dis.getHeight())
        {
            Fragment1 f1 = new Fragment1();
            getFragmentManager().beginTransaction().replace(R.id.LinearLayout1, f1).commit();
        }

        else
        {
            Fragment2 f2 = new Fragment2();
            getFragmentManager().beginTransaction().replace(R.id.LinearLayout1, f2).commit();
        }
    }   
}

四,ViewPager+Fragment實現頁卡滑動
1.首先我們的創建一個適配器FragmentAdapter

package com.example.dfcn.sexmouth.Adpter;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import java.util.List;

/**
 * Created by dfcn on 2018/6/5.
 */

public class FragmentAdpter extends FragmentPagerAdapter {
    private List<Fragment> fragmentList;//創建存儲Fragment的List列表
    public FragmentAdpter(FragmentManager fm,List<Fragment> fragmentList) {
        super(fm);
        this.fragmentList=fragmentList;
    }

    @Override
    public Fragment getItem(int position) {
        return fragmentList.get(position);
    }

    @Override
    public int getCount() {
        return fragmentList.size();
    }
}

2.創建需要滑動的Fragment
其xml佈局文件如下

<FrameLayout 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"
    tools:context="com.example.dfcn.sexmouth.Fragment.OneFragment">

    <!-- : Update blank fragment layout -->
    <TextView
        android:id="@+id/one_fragment"
        android:gravity="center"
        android:background="@color/colorPrimary"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Fragment1" />

</FrameLayout>
<FrameLayout 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:background="#f0f"
    tools:context="com.example.dfcn.sexmouth.Fragment.TwoFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:id="@+id/two_fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Fragment2" />
</FrameLayout>
<FrameLayout 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"
    tools:context="com.example.dfcn.sexmouth.Fragment.ThreeFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:gravity="center"
        android:textSize="50dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="朋友圈" />

</FrameLayout>

3.創建Activity

<?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.example.dfcn.sexmouth.MainActivity">
    <LinearLayout
        android:background="#21616166"
        android:layout_weight="9"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:id="@+id/tv_contack"
            android:text="聯繫人"
            android:textSize="20sp"
            android:gravity="center"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="match_parent" />
        <TextView
            android:id="@+id/tv_chat"
            android:text="聊天"
            android:textSize="20sp"
            android:gravity="center"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="match_parent" />
        <TextView
            android:id="@+id/tv_friend"
            android:text="朋友圈"
            android:textSize="20sp"
            android:gravity="center"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="match_parent" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="6dp">
        <View
            android:id="@+id/v_contack"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="6dp"/>
        <View
            android:id="@+id/v_chat"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="6dp"/>
        <View
            android:id="@+id/v_friend"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="6dp"/>
    </LinearLayout>

    <LinearLayout
    android:layout_weight="1"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    //創建ViewPager
    <android.support.v4.view.ViewPager
        android:id="@+id/main_vp"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </android.support.v4.view.ViewPager>
</LinearLayout>

</LinearLayout>
package com.example.dfcn.sexmouth;

import android.annotation.TargetApi;
import android.graphics.Color;
import android.os.Build;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.example.dfcn.sexmouth.Adpter.FragmentAdpter;
import com.example.dfcn.sexmouth.Fragment.OneFragment;
import com.example.dfcn.sexmouth.Fragment.ThreeFragment;
import com.example.dfcn.sexmouth.Fragment.TwoFragment;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private View v_contack,v_chat,v_friend;
    private TextView tv_contack,tv_chat,tv_friend;
    private ViewPager viewPager;
    private List<Fragment> fragmentList=new ArrayList<>();//實例化List
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
     //初始化控件
        viewPager=findViewById(R.id.main_vp);
        v_contack=findViewById(R.id.v_contack);
        v_chat=findViewById(R.id.v_chat);
        v_friend=findViewById(R.id.v_friend);
        tv_chat=findViewById(R.id.tv_chat);
        tv_contack=findViewById(R.id.tv_contack);
        tv_friend=findViewById(R.id.tv_friend);

        tv_contack.setOnClickListener(this);
        tv_friend.setOnClickListener(this);
        tv_chat.setOnClickListener(this);
         //創建Fragment對象
        OneFragment oneFragment=new OneFragment();
        TwoFragment twoFragment=new TwoFragment();
        ThreeFragment threeFragment=new ThreeFragment();
        //添加Fragment到List中
        fragmentList.add(oneFragment);
        fragmentList.add(twoFragment);
        fragmentList.add(threeFragment);
        //創建適配器
        FragmentAdpter fragmentAdpter=new FragmentAdpter(getSupportFragmentManager(),fragmentList);
        //綁定適配器
        viewPager.setAdapter(fragmentAdpter);


    //滑動字體改變顏色
        v_contack.setBackgroundColor(Color.BLUE);
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onPageSelected(int position) {
                v_contack.setBackgroundColor(Color.WHITE);
                v_chat.setBackgroundColor(Color.WHITE);
                v_friend.setBackgroundColor(Color.WHITE);
                     switch (position){
                         case 0:
                             v_contack.setBackgroundColor(Color.BLUE);
                             break;
                         case 1:
                             v_chat.setBackgroundColor(Color.BLUE);
                             break;
                         case 2:
                             v_friend.setBackgroundColor(Color.BLUE);
                             break;
                             default:
                                 break;

                     }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }
   //點擊改變頁卡
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tv_contack:
                viewPager.setCurrentItem(0);
                break;
            case R.id.tv_chat:
                viewPager.setCurrentItem(1);
                break;
            case R.id.tv_friend:
                viewPager.setCurrentItem(2);
                break;
                default:
                    break;
        }
    }

}

這裏寫圖片描述
五,Fragment的生命週期
這裏寫圖片描述
六,Fragment與Acitvity兩者之間的通信
1.activity傳值到Fragment中
在Activity中創建Bundle數據包,調用Fragment實例的setArguments(bundle) 從而將Bundle數據包傳給Fragment,然後Fragment中調用getArguments獲得 Bundle對象,然後進行解析就可以了

 Bundle bundle=new Bundle();
        bundle.putString("name","和馬");
        oneFragment.setArguments(bundle);

Fragment接受

 Bundle bundle=getArguments();
        String name=bundle.getString("name");
        btn.setText(name);

2.Fragment傳值到Activity中

 public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view=inflater.inflate(R.layout.fragment_one, container, false);
        btn=view.findViewById(R.id.fragment_one_btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MainActivity mainActivity= (MainActivity) getActivity();
                mainActivity.setText("好友");
            }
        });
        return view;

    }

Activity的方法:

  public void setText(String s){
        tv_contack.setText(s);
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章