android小技巧:在activity中實現與綁定的fragment的回調

來源:互聯網
上載者:User

標籤:android   回呼函數   監聽事件   

看到標題你可能會想是一個多麼高大上的技巧呢?其實很一般就是自訂回呼函數.

首先我們知道activity之間的資料傳遞有幾種方式:

一是startActivityForResut()啟動一個activity,當棧頂activity 調用onActivityResult()並且 finish 掉時將會傳遞訊息給啟動該activity的父activity.

二是在使用Fragment時,通過setTargetFragment()和onActivityResult()方法實現兩個fragment之間的資料傳遞.

上述兩種方式對於操作傳遞複雜資料時會很有協助,但是對於簡單資料或者僅僅是喚醒某步操作,並且不一定在子activity或fragment(這裡到子代表由父activity啟動的下一個activity或fragment)finish掉時就進行操作很有協助.


好了,白話了那麼多不相干的,曾睡覺前寫兩行代碼貼上讓大家感受一下:

我這裡首先建立了一個抽象類別繼承自V4擴充庫的FragmentActivity來管理每個Fragment的建立

package com.example.icedcap.fragmentcallbackdemo;import android.os.Bundle;import android.support.v4.app.Fragment;import android.support.v4.app.FragmentActivity;import android.support.v4.app.FragmentManager;/** * Created by icedcap on 14-11-18. */public abstract class SingleFragment extends FragmentActivity {    public abstract Fragment createFragment();    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_my);        FragmentManager fm = getSupportFragmentManager();        Fragment mFragment = fm.findFragmentById(R.id.container);        if (mFragment == null){            mFragment = createFragment();            fm.beginTransaction().add(R.id.container, mFragment).commit();        }    }}

這樣我在主activity中只需繼承該抽象類別並且實現createFragment方法就能輕鬆建立一個Fragment並且將其添加到R.id.container容器上了.

    @Override    public Fragment createFragment() {        return new IndexFragment();    }

對於Fragment很簡單我只加了一個TextView和一個Button控制項,當點擊Button時,喚醒回呼函數,使activity的回呼函數進行工作.

package com.example.icedcap.fragmentcallbackdemo;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.ViewGroup;import android.widget.Button;/** * Created by icedcap on 14-11-18. */public class IndexFragment extends Fragment {    private IndexListener mListener;    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {        View v = inflater.inflate(R.layout.fragment_index, container, false);        Button button = (Button) v.findViewById(R.id.index_button);        button.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                mListener.onIndexListener("Call Back to My Implementer");            }        });        return v;    }    public interface IndexListener{        public void onIndexListener(String str);    }    //初始化mListener    @Override    public void onAttach(Activity activity) {        super.onAttach(activity);        try {            mListener = (IndexListener) activity;        }catch (ClassCastException e){            throw new ClassCastException(activity.toString() + " must implement IndexListener");        }    }}

在主activity完成回呼函數的任務

package com.example.icedcap.fragmentcallbackdemo;import android.support.v4.app.Fragment;import android.util.Log;public class MyActivity extends SingleFragment implements IndexFragment.IndexListener{    private static final String TAG = "MyActivity";    @Override    public Fragment createFragment() {        return new IndexFragment();    }    @Override    public void onIndexListener(String str) {        Log.d(TAG, "From the Fragment message: " + str);    }}

當點擊Fragment中的Button時,Logcat會列印這樣一句話:

From the Fragment message: Call Back to My Implementer

好了,代碼結束!

這個例子看上去貌似沒啥意義,但是對於一些應用場合還是很重要的,例如,在檔案管理工具中搜尋功能,當鍵入一些字串時,就會立即返回結果使用者不必輸入整個要查詢的檔案名稱就能檢索出結果來,正是利用EditText的addTextChangeListener事件並手動添加了後台檢索方法的類來監聽afterTextchange函數裡所擷取到底殘缺字串.

好了,弄明白監聽對象和喚醒監聽對象的兩個類後使很容易寫出簡介易懂的代碼的.




android小技巧:在activity中實現與綁定的fragment的回調

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.