Activity 與 Fragment 之間相互通訊

歡迎轉載,但請保留文章原始出處→_→ html

生命壹號:http://www.cnblogs.com/smyhvae/ java

文章來源:http://www.cnblogs.com/smyhvae/p/4000390.htmlandroid

聯繫方式:smyhvae@163.com web

 

【正文】app


1、接口回調的簡單引入:
ide

咱們先來看一個簡單的接口回調的例子:佈局

新建一個Java工程,而後新建一個包。而後新建一個A.java文件:this

A.java代碼以下:spa

複製代碼

package com.cn.callback;
public class A {
    public A() {
        
    }
    
    //下載圖片的操做
    public void loadImage(String image_path,final CallBack callBack) {
        new Thread(new Runnable(){
            public void run() {
                // TODO Auto-generated method stub
                String msg = "Hello world";
                callBack.getResult(msg);                
            }
            
        }).start();
    }
    //接口回調我以爲很好理解,那就是:if you call me, i will call you back.
    
    public interface CallBack {
        public void getResult(String result);
    }
}

複製代碼

第21至23行就是回調方法。.net

新建B.java,代碼以下:

複製代碼

package com.cn.callback;
import com.cn.callback.A.CallBack;
public class B {
    public B(){
        
    }
    
    public static void main(String args[]) {
        A a = new A();
        a.loadImage("http://www.baidu.com/a.gif", new CallBack() {
            public void getResult(String result) {
                // TODO Auto-generated method stub
                System.out.println(result);
            }
            
        });
    }
}

複製代碼

最後程序運行的結果以下:

關於接口回調,有一個博客,不過如今還不能徹底理解,附上連接:

一個經典例子讓你不折不扣理解java回調機制:http://blog.csdn.net/xiaanming/article/details/8703708

 

2、Fragment和Activity的交互:

一、在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的核心代碼以下:

複製代碼

public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_left, null);    
        button = (Button) view.findViewById(R.id.button1);
        button.setOnClickListener(new OnClickListener() {            
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                EditText editText = (EditText) getActivity().findViewById(R.id.editText);
                Toast.makeText(getActivity(), editText.getText().toString(), 1).show();
            }
        });
        return view;
    }

複製代碼

第09行代碼是核心,經過getActivity()方法來得到Activity的實例,而後就能夠調用findViewById()的方法獲得其中的EditText控件。

二、在Activity中調用Fragment中的方法:(要用到接口回調

activity也能夠得到一個fragment的引用,從而調用fragment中的方法。得到fragment的引用要用FragmentManager,以後能夠調用findFragmentById() 或者 findFragmentByTag()。例如:

ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);

 

具體例子稍後再講。

三、Fragment與Fragment之間的通訊:

既然Fragment和Activity之間的通訊問題解決了,那Fragment與Fragment之間的通訊也沒有那麼複雜。基本思路是:

首先在一個Fragment中能夠獲得與它相關聯的Activity,而後再經過這個Activity去獲取另一個Fragment的實例,這樣就實現了不一樣Fragment之間的通訊。

3、建立事件回調(在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的代碼以下:

複製代碼

<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的代碼以下:

複製代碼

package com.example.m01_fragment05;
import com.example.m01_fragment05.LeftFragment.CallBack;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
    private FragmentManager manager;
    private FragmentTransaction transaction;
    private Button button;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);        
        button = (Button)findViewById(R.id.button);
        
        //動態加載leftFragment
        manager = getFragmentManager();
        transaction = manager.beginTransaction();
        final LeftFragment leftFragment = new LeftFragment();
        transaction.add(R.id.left, leftFragment, "left");
        transaction.commit();
        button.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                //點擊按鈕後,經過接口回調,獲取fragment當中EditText的值,並彈出吐司
                leftFragment.getEditText(new CallBack(){
                    @Override
                    public void getResult(String result) {
                        // TODO Auto-generated method stub
                        Toast.makeText(MainActivity.this, result, 1).show();
                    }                    
                });
            }
        });
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }    
}

複製代碼

咱們在Activity當中動態加載Fragment,而後點擊按鈕,經過接口回調,獲取fragment當中EditText的值,並彈出吐司。

程序運行後,在左側的Fragment的EditText當中輸入值,點擊右側的按鈕,彈出吐司,效果以下:

 

【索引】

若是你對本文存在疑惑,請參考本人關於Fragment的系列文章:(不斷更新)

Android系列之Fragment(一)----Fragment加載到Activity當中

Android系列之Fragment(二)----Fragment的生命週期和返回棧

Android系列之Fragment(三)----Fragment和Activity之間的通訊(含接口回調)

Android系列之Fragment(四)----ListFragment的使用

相關文章
相關標籤/搜索