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


看到標題你可能會想是一個多么高大上的技巧呢?事實上非常一般就是自己定義回調函數.

首先我們知道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非常easy我僅僅加了一個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函數里所獲取究竟殘缺字符串.

好了,弄明確監聽對象和喚醒監聽對象的兩個類后使非常easy寫出簡單介紹易懂的代碼的.





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM