Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 關於android開發 >> Fragment的生命周期和Activity之間的通信以及使用,fragmentactivity

Fragment的生命周期和Activity之間的通信以及使用,fragmentactivity

編輯:關於android開發

Fragment的生命周期和Activity之間的通信以及使用,fragmentactivity


Fragment通俗來講就是碎片,不能單獨存在,意思就是說必須依附於Activity,一般來說有兩種方式把Fragment加到Activity,分為靜態,動態。

靜態即為右鍵單擊,建立一個Fragment,選擇Blank,在Activity布局中直接加fragment,name屬性直接指向之前建立的Fragment,這就添加上了Fragment,這種較為簡單。

動態:

我們要做的是在Activity中添加一個Fragment,Fragment中有兩個按鈕,當按下按鈕時分別切換不同的Fragment,注意,切換不同的Fragment的代碼在Activity中寫。

實現Fragment和Activity之間的通信,步驟一般分為五步,1、在Fragment中聲明一個接口。 2、在Activity中實現在Fragment中聲明的接口。

3、在Fragment中聲明一個接口對象。 4、在Fragment的生命周期中onAttach方法中判斷當前Activity是否實現了此Fragment中聲明的接口

5、調用Activity中實現的方法 (接口對象.方法名)

 

首先,建立一個名為OneFragment的Fragment,在右鍵單擊建立時勾選Include fragment factory methods 和Include interface callback,這樣會自動添加相關代碼,省掉很多時間.再在新建立的Fragment裡添加兩個按鈕,設置Id。

布局代碼如下

<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.administrator.homeworepar.Fragment.OneFragment">

<!-- TODO: Update blank fragment layout -->
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/bt1"
android:text="好友"/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/bt2"
android:text="消息"
android:layout_gravity="center_horizontal|top" />

</FrameLayout>


下面為Fragment的代碼
package com.example.administrator.homeworepar.Fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.example.administrator.homeworepar.R;

/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link OneFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link OneFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class OneFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;

private OnFragmentInteractionListener mListener;

public OneFragment() {
// Required empty public constructor
}

/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment OneFragment.
*/
// TODO: Rename and change types and number of parameters
public static OneFragment newInstance(String param1, String param2) {
OneFragment fragment = new OneFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}

@Override
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);
Button bt1= (Button) view.findViewById(R.id.bt1); // 實現的功能是的那個按下按鈕時,會調用ACtivity中的changFragment方法
bt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mListener.changFragment(1);
}
});
Button bt2= (Button) view.findViewById(R.id.bt2);
bt2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mListener.changFragment(2);
}
});
return view;
}



@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) { 判斷是否實現了接口,如果實現了接 口,就把Activity轉換為接口的對 象,這樣就可以調用方 法
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}

@Override
public void onDetach() {
super.onDetach();
mListener = null;
}

/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener { // 此段為自動添加的接口,在接口中實現一個方法修改完後會有其他代碼出錯,只要 把出錯代碼刪掉即可。
// TODO: Update argument type and name
void changFragment(int which);
}
 

再建立一個Activity,

package com.example.administrator.homeworepar.Fragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;

import com.example.administrator.homeworepar.R;

public class Fragment2Activity extends AppCompatActivity implements OneFragment.OnFragmentInteractionListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment2);
}
@Override
public void changFragment(int which) {
if(which==1){
Fragment fragment1=new BlankFragment(); //實現Fragment中的方法,當得到的值為1時,把BlankFragment填充 //到Id為fl2中的FrameLayout中,
getSupportFragmentManager()
                    .beginTransaction().replace(R.id.fl2,fragment1).commit();
}else if(which==2){
Fragment fragment2=new SecondFragment();
getSupportFragmentManager()
.beginTransaction().replace(R.id.fl2,fragment2).commit();
}
}
}





ACtivity布局代碼如下
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.administrator.homeworepar.Fragment.Fragment2Activity">
<fragment
android:layout_width="match_parent"
android:layout_height="50dp"
android:name="com.example.administrator.homeworepar.Fragment.OneFragment"
android:id="@+id/fragment3" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/fl2"
android:layout_below="@+id/fragment3">

</FrameLayout>
</RelativeLayout>
這樣就可以實現ACtivity與Fragment間的通信,另外Fragment還有和Activity一樣還有生命周期的問題

方法名 說明
onAttach () Fragment被附加到Activity的時,調用此函數,在這個方法中可以獲得宿主Activity。
onCreate () Fragment被創建的時,調用此函數。
onCreateView () Fragment的布局加載時,調用此函數。
onActivityCreated () 當宿主Activity啟動完畢後,調用此函數。
onStart () 啟動Fragment時,調用此函數。
onResume () Fragment恢復時,調用此函數。
onPause () Fragment暫停時,調用此函數。
onStop() Fragment停止時,調用此函數。
onDestroyView() 銷毀Fragment中的View控件時,調用此函數。
onDestroy() 銷毀Fragment時,調用此函數。
onDetach() Fragment從Activity脫離時,調用此函數

 

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved