1. 程式人生 > >Android匯入design.v4包,Fragment生命週期,靜態/動態載入

Android匯入design.v4包,Fragment生命週期,靜態/動態載入

工作內容:

1.Fragment類與Activity生命週期
2.Fragment的動態載入(重要)和靜態載入
3.Fragment與ViewPager的聯合使用

學習分享:

一、Fragment類與Activity生命週期

執行順序:

Activity_onCreate
Fragment_onCreate
Fragment_onCreateView
Fragment_onViewCreated
Fragment_onActivityCreated
Activity_onStart
Fragment_onStart
Activity_onResume
Fragment_onResume
點選了list圖示,進入home介面


Fragment_onPause
Activity_onPause
Fragment_onStop
Activity_onStop
回到test頁面
Activity_onRestart
 Activity_onStart
Fragment_onStart
Activity_onResume
Fragment_onResume
點返回鍵銷燬Activity
Fragment_onPause
Activity_onPause
Fragment_onStop
Activity_onStop
Fragment_onDestroyView
Fragment_onDestroy
Fragment_onDestroy
Activity_onDestroy

二、Fragment的靜態載入和動態載入(重要)

靜態載入步驟:(很少用到)

<?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="wrap_content"
android:padding="6dp"
android:orientation="horizontal">
    <ImageView
android:layout_width="30dp" android:layout_height="30dp" android:background="@drawable/reset" android:id="@+id/iv_frag2" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="News " android:textSize="30sp" android:layout_marginLeft="10dp" android:id="@+id/tv_frag2" /> </LinearLayout>
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
/**
 * Created by Administrator on 2016/9/1.
 */
public class Frag_2 extends Fragment {
    private View view ;
    private TextView tv_frag2;
    private ImageView iv_frag2;
/**
     * 必須重寫的方法
     * @param inflater 用於解析View 【可以理解為:將佈局檔案與java檔案繫結】     * @param container 父容器(可以是FrameLayout,LinearLayout等等)
     * @param savedInstanceState bundle物件用於傳值
     * @return
*/@Nullable
    @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.frag_2,container,false);
        return view;
}

    /**
     * 在onCreateView之後執行
     * @param view onCreateView中解析得到的view(一個佈局檔案)
     * @param savedInstanceState
*/@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
initView();
}

    private void initView() {
        tv_frag2 = (TextView)view.findViewById(R.id.tv_frag2);
iv_frag2 = (ImageView)view.findViewById(R.id.iv_frag2);
iv_frag2.setOnClickListener(new View.OnClickListener() {
            @Override
public void onClick(View v) {
                Log.e("LOGKEY---->","點選了frag2的書信圖示");
}
        });
}
}
import android.os.Bundle;import android.support.annotation.Nullable;import android.support.v4.app.Fragment;import android.util.Log;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.TextView;/** * Created by Administrator on 2016/9/1. */public class Frag_2 extends Fragment { private View view ; private TextView tv_frag2; private ImageView iv_frag2;/** * 必須重寫的方法 * @param inflater 用於解析View * @param container 父容器(可以是FrameLayout,LinearLayout等等) * @param savedInstanceState bundle物件用於傳值 * @return*/@Nullable @Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.frag_2,container,false); return view;} /** * 在onCreateView之後執行 * @param view onCreateView中解析得到的view(一個佈局檔案) * @param savedInstanceState*/@Overridepublic void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState);initView();} private void initView() { tv_frag2 = (TextView)view.findViewById(R.id.tv_frag2);iv_frag2 = (ImageView)view.findViewById(R.id.iv_frag2);iv_frag2.setOnClickListener(new View.OnClickListener() { @Overridepublic void onClick(View v) { Log.e("LOGKEY---->","點選了frag2的書信圖示");} });}} 使用這個fragment:在Activity的佈局檔案中加入下面程式碼
<fragment
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:name="com.plane.people.planebattle.Frag_2"
android:id="@+id/fragment"
android:layout_gravity="center_horizontal" />

Fragment動態載入(重要——常用)

這裡講幾個Fragment的實現類動態載入進一個FrameLayout

xml檔案:(放了一個ImageView)

frag_spring.xml 對應Fragment類:public class Fragment_spring extends Fragment{}

frag_summer.xml 對應Fragment類:public class Fragment_summer extends Fragment{}

frag_autumn.xml 對應Fragment類:public class Fragment_autumn extends Fragment{}

frag_winter.xml 對應Fragment類:public class Fragment_winter extends Fragment{}

frag_spring.xml程式碼:(其餘幾個相同,只是放的圖片不同)

<?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">
    <ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/spring"
/>
</LinearLayout>
Java程式碼:

這裡繼承的Fragment 選擇包:android.support.v4.app.Fragment

原因:Fragment 放入ViewPager中時可以使用一個介面卡:android.support.v4.app.FragmentPagerAdapter,這樣可以很簡單的完成他們之間的融合。

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.ImageView;
import android.widget.Toast;
/**
 * Created by Administrator on 2016/9/1.
 */
public class Fragment_spring extends Fragment {
    @Nullable
    @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.frag_spring,container,false);
}

    @Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
ImageView imageView = (ImageView)view.findViewById(R.id.iv_spring);
imageView.setOnClickListener(new View.OnClickListener() {
            @Override
public void onClick(View v) {
                Toast.makeText(getActivity(), "春天來了", Toast.LENGTH_SHORT).show();
}
        });
}
}
Activity的程式碼:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
public class FragmentTestActivity extends AppCompatActivity implements View.OnClickListener{
    private FrameLayout frameLayout;
    private Fragment fragment_sp,fragment_su,fragment_au,fragment_wi;
    private FragmentManager fm;
    private FragmentTransaction ft;
    private int [] tvIDs = {R.id.tv_sp,R.id.tv_su,R.id.tv_au,R.id.tv_wi};//TextView的id陣列
@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_view_pager);
initListener();
initData();
}

    //新增點選事件
private void initListener() {
        for (int i = 0; i < tvIDs.length; i++) {
            findViewById(tvIDs[i]).setOnClickListener(this);
}
    }
    //初始化資料
private void initData() {
        /**
         * (引入包為android.app時可以使用getFragmentManager()獲取FragmentManager)
         * 使用getSupportFragmentManager()獲取 FragmentManager 需要當前Activity繼承FragmentActivity         * 或其子類(AppCompatActivity是其子類)         * 【引入import android.support.v4.app.類名,需使用使用getSupportFragmentManager()】         */fm = getSupportFragmentManager();
frameLayout = (FrameLayout)findViewById(R.id.frame_test);
//設定預設顯示
ft = fm.beginTransaction();
fragment_sp = new Fragment_spring();
ft.replace(R.id.frame_test,fragment_sp);
ft.commit();
}

    /**
     * 實現點選幾個TextView顯示對應的Fragment
     * @param v
*/
@Override
public void onClick(View v) {
        ft = fm.beginTransaction();     //開始事務(提交一次就需要開啟一次)
switch (v.getId()){
            case R.id.tv_sp:
                if(fragment_sp == null){
                    fragment_sp = new Fragment_spring();
}
                /**
                 * 用fragment_sp來替換FrameLayout中的內容
                 * ft.replace 相當於先 ft.remove 後 ft.add
                 */ft.replace(R.id.frame_test,fragment_sp);
                break;
            case R.id.tv_su:
                if(fragment_su == null){
                    fragment_su = new Fragment_summer();
}
                ft.replace(R.id.frame_test,fragment_su);
                break;
            case R.id.tv_au:
                if(fragment_au == null){
                    fragment_au = new Fragment_autumn();
}
                ft.replace(R.id.frame_test,fragment_au);
                break;
            case R.id.tv_wi:
                if(fragment_wi == null){
                    fragment_wi = new Fragment_winter();
}
                ft.replace(R.id.frame_test,fragment_wi);
                break;
}
        ft.commit();    //必須要—用於提交事務
}
}
演示效果:【點選螢幕下方的文字顯示對應的Fragment,點選圖片,提示“春天來了”,“夏天來了”等字樣】