標籤:android   style   blog   class   code   c   
簡介:
為什麼要用Fragment?使用Fragment可以在一個Activity中實現不同的介面。Fragment與Fragment之間的動畫切換,遠比Activity與Activity之間的動畫切換變化方式多。很多時候,我們通過使用一個Activity,切換多個Fragment。本次部落格,主要列舉一下Fragment與它的Activity之間進行資料交換的方式。
1.Fragment中通過getActivity()然後進行強制轉化,調用Activity中的公有方法
((XXXXActivity)getActivity()).fun();
2.Activity在切換Fragment的時候,通過setArguments向Fragment傳遞參數,Fragment通過getArguments();獲得從activity中傳遞過來的值
3.Activity實現一個介面,Fragment在onAttach方法中,將該Activity轉化為該介面,在需要調用的時候回調。
注意:本Demo是通過FragmentManager來管理Fragment的,通過FragmentManager管理,我們建立Fragment和銷毀Fragment的時候,可以通過棧的方式:
a.FragmentTransaction的add方法,添加一個Fragment
b.FragmentTransaction的popBackStack()彈出該Fragment
示範執行個體:
fragment1.xml
<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:background="#FFFFFFFF"    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.testfragment.MainActivity$PlaceholderFragment" >    <TextView        android:id="@+id/tv"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentTop="true"        android:text="fragment1" />    <Button        android:id="@+id/btn"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_below="@id/tv"        android:text="跳轉到Fragment2" /></RelativeLayout>
MyFragment1.java
/* * $filename: MyFragment.java,v $ * $Date: 2014-5-16  $ * Copyright (C) ZhengHaibo, Inc. All rights reserved. * This software is Made by Zhenghaibo. */package com.example.testfragment;import android.app.Activity;import android.os.Bundle;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.View.OnClickListener;import android.view.ViewGroup;import android.widget.Button;/* *@author: ZhengHaibo   *web:     http://blog.csdn.net/nuptboyzhb *mail:    [email protected] *2014-5-16  Nanjing,njupt,China */public class MyFragment1 extends Fragment {FragmentCallBack fragmentCallBack = null;Button btn;@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {View rootView = inflater.inflate(R.layout.fragment1, container,false);btn = (Button)rootView.findViewById(R.id.btn);btn.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubfragmentCallBack.callbackFun1(null);}});return rootView;}@Overridepublic void onAttach(Activity activity) {// TODO Auto-generated method stubsuper.onAttach(activity);fragmentCallBack = (MainActivity)activity;}}
fragment2.xml
<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:background="#FFFFFFFF"    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.testfragment.MainActivity$PlaceholderFragment" >    <TextView        android:id="@+id/tv"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentTop="true"        android:text="fragment2" />    <Button        android:id="@+id/btn1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_below="@id/tv"        android:text="直接調用Activity" />    <Button        android:id="@+id/btn2"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_below="@id/btn1"        android:text="回調Activity" /></RelativeLayout>
MyFragment2.java
/* * $filename: MyFragment.java,v $ * $Date: 2014-5-16  $ * Copyright (C) ZhengHaibo, Inc. All rights reserved. * This software is Made by Zhenghaibo. */package com.example.testfragment;import android.app.Activity;import android.os.Bundle;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.View.OnClickListener;import android.view.ViewGroup;import android.widget.Button;import android.widget.Toast;/* *@author: ZhengHaibo   *web:     http://blog.csdn.net/nuptboyzhb *mail:    [email protected] *2014-5-16  Nanjing,njupt,China */public class MyFragment2 extends Fragment {FragmentCallBack fragmentCallBack = null;Button btn1;Button btn2;@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {View rootView = inflater.inflate(R.layout.fragment2, container,false);Bundle data = getArguments();//獲得從activity中傳遞過來的值Toast.makeText(getActivity(), data.getString("TEXT"), Toast.LENGTH_SHORT).show();btn1 = (Button)rootView.findViewById(R.id.btn1);btn1.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// 直接調用Activity中的方法((MainActivity)getActivity()).changeButtonColor();}});btn2 = (Button)rootView.findViewById(R.id.btn2);btn2.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// 回調的方式fragmentCallBack.callbackFun2(null);}});return rootView;}@Overridepublic void onAttach(Activity activity) {// TODO Auto-generated method stubsuper.onAttach(activity);fragmentCallBack = (MainActivity)activity;}}
回調介面:
/* * $filename: FragmentCallBack.java,v $ * $Date: 2014-5-16  $ * Copyright (C) ZhengHaibo, Inc. All rights reserved. * This software is Made by Zhenghaibo. */package com.example.testfragment;import android.os.Bundle;/* *@author: ZhengHaibo   *web:     http://blog.csdn.net/nuptboyzhb *mail:    [email protected] *2014-5-16  Nanjing,njupt,China */public interface FragmentCallBack {public void callbackFun1(Bundle arg);public void callbackFun2(Bundle arg);}
main.xml
<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" >    <Button        android:id="@+id/btn"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_alignParentBottom="true"        android:text="切換" />    <RelativeLayout        android:id="@+id/rl_container"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_above="@id/btn" /></RelativeLayout>
MainActivity.java
package com.example.testfragment;import android.graphics.Color;import android.os.Bundle;import android.support.v4.app.Fragment;import android.support.v4.app.FragmentManager;import android.support.v4.app.FragmentTransaction;import android.support.v7.app.ActionBarActivity;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class MainActivity extends ActionBarActivity implements FragmentCallBack{private Button btn;private MyFragment1 fragment1;private MyFragment2 fragment2;private FragmentManager fragmentManager;private Fragment currentFragment;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);fragmentManager = getSupportFragmentManager();FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);fragment1 = new MyFragment1();Bundle data = new Bundle();data.putString("TEXT", "這是Activiy通過Bundle傳遞過來的值");fragment1.setArguments(data);//通過Bundle向Activity中傳遞值fragmentTransaction.add(R.id.rl_container,fragment1);//將fragment1設定到布局上fragmentTransaction.addToBackStack(null);fragmentTransaction.commitAllowingStateLoss();currentFragment = fragment1;//初始化button控制項btn = (Button)findViewById(R.id.btn);btn.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {if(currentFragment instanceof MyFragment1){switchFragment();}else{//當前是fragment2,因此,只需要將fragment2出棧即可變成fragment1fragmentManager.popBackStack();currentFragment = fragment1;}}});}/** * 切換Fragment */private void switchFragment(){if(null == fragment2){//可以避免切換的時候重複建立fragment2 = new MyFragment2();}Bundle data = new Bundle();data.putString("TEXT", "傳遞給fragment2");fragment2.setArguments(data);FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);fragmentTransaction.add(R.id.rl_container,fragment2);fragmentTransaction.addToBackStack(null);fragmentTransaction.commitAllowingStateLoss();currentFragment = fragment2;}public void changeButtonColor(){btn.setBackgroundColor(Color.RED);}@Overridepublic void callbackFun1(Bundle arg) {// TODO Auto-generated method stubswitchFragment();//通過回調方式切換}@Overridepublic void callbackFun2(Bundle arg) {// TODO Auto-generated method stubchangeButtonColor();//通過回調方式調用Activity中的方法}}
初始畫面
切換到第二個Fragment之後,通過Fragment2回調,改變按鈕背景後的。
注意:
1.直接在Fragment中通過getActivity然後強轉Activity的方式調用Activity的方法,這個方式不推薦!因為這會使Fragment的適配性變差。
解決方案:在使用之前,使用instanceof 判斷一下Activity的類型
2.FragmentTransaction通過使用setCustomAnimations方法,可以為Fragment的切換增添各種不同的動畫。變化方式遠比Activity與Activity之間的切換動畫要多。
3.多個Fragment之間,可以通過Activity複用很多代碼,提高效率。
4.我們還可以通過ViewPager來管理Fragment,通過Adapter添加多個Fragment,然後通過setcurrentitem進行切換。我們同樣可以通過setArguments向Fragment傳遞資料。