【聲明】
歡迎轉載,但請保留文章原始出處→_→
原文[這里](http://www.cnblogs.com/smyhvae/p/4000390.html)
【正文】
#### 一、接口回調的簡單引入:
我們先來看一個簡單的接口回調的例子:
新建一個Java工程,然后新建一個包。然后新建一個A.java文件:
A.java代碼如下:
~~~
1 package com.cn.callback;
2
3 public class A {
4 public A() {
5
6 }
7
8 //下載圖片的操作
9 public void loadImage(String image_path,final CallBack callBack) {
10 new Thread(new Runnable(){
11
12 public void run() {
13 // TODO Auto-generated method stub
14 String msg = "Hello world";
15 callBack.getResult(msg);
16 }
17
18 }).start();
19 }
20
21 public interface CallBack {
22 public void getResult(String result);
23 }
24 }
~~~
第21至23行就是回調方法。
新建B.java,代碼如下:
~~~
1 package com.cn.callback;
2
3 import com.cn.callback.A.CallBack;
4
5 public class B {
6 public B(){
7
8 }
9
10 public static void main(String args[]) {
11 A a = new A();
12 a.loadImage("http://www.baidu.com/a.gif", new CallBack() {
13 public void getResult(String result) {
14 // TODO Auto-generated method stub
15 System.out.println(result);
16 }
17
18 });
19 }
20 }
~~~
最后程序運行的結果如下:

關于接口回調,有一個博客,不過現在還不能完全理解,附上鏈接:
一個經典例子讓你徹徹底底理解java回調機制:http://blog.csdn.net/xiaanming/article/details/8703708
#### 二、Fragment和Activity的交互:
#### 1、在Fragment中調用Activity中的方法:
Fragment可以通過getActivity()方法來獲得Activity的實例,然后就可以調用一些例如findViewById()之類的方法。例如:
`View listView = getActivity().findViewById(R.id.list);`
但是注意調用getActivity()時,fragment必須和activity關聯(attached to an activity),否則將會返回一個null。
另外,當碎片中需要使用Context對象時,也可以使用getActivity()方法,因此獲取到的活動本身就是一個Context對象。
【實例】在Activity的EditText中輸入一段文本,這個時候,點擊Fragment中的按鈕,讓它彈出吐司,顯示出對應的文本。
**其實就是讓Activity中的文本顯示在Fragment中**,Fragment的核心代碼如下:
~~~
1 public View onCreateView(LayoutInflater inflater, ViewGroup container,
2 Bundle savedInstanceState) {
3 View view = inflater.inflate(R.layout.fragment_left, null);
4 button = (Button) view.findViewById(R.id.button1);
5 button.setOnClickListener(new OnClickListener() {
6 @Override
7 public void onClick(View v) {
8 // TODO Auto-generated method stub
9 EditText editText = (EditText) getActivity().findViewById(R.id.editText);
10 Toast.makeText(getActivity(), editText.getText().toString(), 1).show();
11 }
12 });
13
14 return view;
15 }
~~~
第09行代碼是核心,通過getActivity()方法來獲得Activity的實例,然后就可以調用findViewById()的方法得到其中的EditText控件。
#### 2、在Activity中調用Fragment中的方法:(要用到**接口回調**)
activity也可以獲得一個fragment的引用,從而調用fragment中的方法。獲得fragment的引用要用FragmentManager,之后可以調用findFragmentById() 或者 findFragmentByTag()。例如:
`ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);`
**具體例子稍后再講。**
#### 3、Fragment與Fragment之間的通信:
既然Fragment和Activity之間的通信問題解決了,那Fragment與Fragment之間的通信也沒有那么復雜。基本思路是:
**首先在一個Fragment中可以得到與它相關聯的Activity,然后再通過這個Activity去獲取另外一個Fragment的實例,**這樣就實現了不同Fragment之間的通信。
#### 三、創建事件回調(在Activity中獲取Fragment中的值):
**一些情況下,可能需要fragment和activity共享事件,一個比較好的做法是在fragment里面定義一個回調接口,然后要求宿主activity實現這個接口。**當activity通過這個接口接收到一個回調,它可以讓同布局中的其他fragment分享這個信息。
例如,一個新聞顯示應用在一個activity中有兩個fragment,一個fragment A顯示文章題目的列表,一個fragment B顯示文章。所以當一個文章被選擇的時候,fragment A必須通知activity,然后activity通知fragment B,讓它顯示這篇文章。(例子的代碼見官方文檔)
我們現在舉一個其他的例子:
【實例】在Fragment中輸入值,點擊Activity中的按鈕,彈出吐司,顯示之前輸入的值。**其實就是讓Fragment中的文本顯示在Activity中**
我們在平板的左側加入一個fragment,完整代碼如下:
fragment_left.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"
android:orientation="vertical" >
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
</LinearLayout>
~~~
其實就是加了一個EditText,方便在里面輸入文本內容。
然后在frament中加一個接口回調,讓它在Activity當中調用,方便獲取輸入文本的值。LeftFragment.java的代碼如下:
~~~
1 package com.example.m01_fragment05;
2
3 import android.app.Fragment;
4 import android.os.Bundle;
5 import android.view.LayoutInflater;
6 import android.view.View;
7 import android.view.ViewGroup;
8 import android.widget.Button;
9 import android.widget.EditText;
10
11 public class LeftFragment extends Fragment {
12
13 private Button button;
14 private EditText editText;
15
16 @Override
17 public void onCreate(Bundle savedInstanceState) {
18 super.onCreate(savedInstanceState);
19 }
20
21 @Override
22 public View onCreateView(LayoutInflater inflater, ViewGroup container,
23 Bundle savedInstanceState) {
24 View view = inflater.inflate(R.layout.fragment_left, null);
25 editText = (EditText) view.findViewById(R.id.editText1);
26 return view;
27 }
28
29 @Override
30 public void onPause() {
31 super.onPause();
32 }
33
34 //接口回調
35 public void getEditText(CallBack callBack) {
36 String msg = editText.getText().toString();
37 callBack.getResult(msg);
38 }
39
40 public interface CallBack {
41 public void getResult(String result);
42 }
43 }
~~~
代碼解釋如下:
第25行:**一定要為editText加一個id**,不然會報空指針異常的錯誤;
34至42行:添加一個接口回調,用于獲取文本的值,然后稍后再Activity當中進行調用。
activity_main.xml的代碼如下:
~~~
<LinearLayout 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:orientation="horizontal"
tools:context=".MainActivity" >
<LinearLayout
android:id="@+id/left"
android:layout_width="224dp"
android:layout_height="match_parent"
android:background="#CCCCCC"
android:orientation="vertical" >
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="獲得Fragment的值" />
</LinearLayout>
</LinearLayout>
~~~
其實一共就兩個線性布局,左邊的現性布局留給fragment,右邊的線性性局留給Activity。
MainActivity.java的代碼如下:
~~~
1 package com.example.m01_fragment05;
2
3 import com.example.m01_fragment05.LeftFragment.CallBack;
4
5 import android.app.Activity;
6 import android.app.FragmentManager;
7 import android.app.FragmentTransaction;
8 import android.os.Bundle;
9 import android.view.Menu;
10 import android.view.View;
11 import android.view.View.OnClickListener;
12 import android.widget.Button;
13 import android.widget.Toast;
14
15 public class MainActivity extends Activity {
16 private FragmentManager manager;
17 private FragmentTransaction transaction;
18 private Button button;
19 @Override
20 protected void onCreate(Bundle savedInstanceState) {
21 super.onCreate(savedInstanceState);
22 setContentView(R.layout.activity_main);
23 button = (Button)findViewById(R.id.button);
24
25 //動態加載leftFragment
26 manager = getFragmentManager();
27 transaction = manager.beginTransaction();
28 final LeftFragment leftFragment = new LeftFragment();
29 transaction.add(R.id.left, leftFragment, "left");
30 transaction.commit();
31 button.setOnClickListener(new OnClickListener() {
32
33 @Override
34 public void onClick(View v) {
35 //點擊按鈕后,通過接口回調,獲取fragment當中EditText的值,并彈出吐司
36 leftFragment.getEditText(new CallBack(){
37 @Override
38 public void getResult(String result) {
39 // TODO Auto-generated method stub
40 Toast.makeText(MainActivity.this, result, 1).show();
41 }
42 });
43 }
44 });
45 }
46
47 @Override
48 public boolean onCreateOptionsMenu(Menu menu) {
49 // Inflate the menu; this adds items to the action bar if it is present.
50 getMenuInflater().inflate(R.menu.main, menu);
51 return true;
52 }
53 }
~~~
我們在Activity當中動態加載Fragment,然后點擊按鈕,通過接口回調,獲取fragment當中EditText的值,并彈出吐司。
程序運行后,在左側的Fragment的EditText當中輸入值,點擊右側的按鈕,彈出吐司,效果如下:
