zoukankan      html  css  js  c++  java
  • 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写出简单介绍易懂的代码的.




  • 相关阅读:
    Effective C# 学习笔记(三十五) 了解PLINQ如何实现并行算法
    Effective C# 学习笔记(三十八)理解Dynamic的得与失
    转单例的分析
    获取系统当前音量 和 监听系统音量 ios
    (转) iphone开发资源汇总
    xcode show line numbers
    为了编程方便的效率宏定义的一些代码
    ios6下cocos2d & ipad 调用摄像头报错问题 (在竖屏情况下调用Camera 会导致转屏)
    转KVC
    不记住的
  • 原文地址:https://www.cnblogs.com/mthoutai/p/7094977.html
Copyright © 2011-2022 走看看