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写出简单介绍易懂的代码的.
android小技巧:在activity中实现与绑定的fragment的回调的更多相关文章
- android 编程小技巧(持续中)
first: Intent跳转一般存用于Activity类,可是若要在非activity类里跳转的话,解决方法是在startActivity(intent)前加mContext即上下文,终于为 ...
- Android小技巧
一.android:clipChildren属性 效果图 看到这个图时你可以先想想如果是你,你怎么实现这个效果.马上想到用RelativeLayout?NO,NO,NO,,, 实现代码 <?xm ...
- android开发之在activity中控制另一个activity的UI更新
转自:http://blog.csdn.net/jason0539/article/details/18075293 第一种方法: 遇到一个问题,需要在一个activity中控制另一个acitivit ...
- iOS开发小技巧 - UILabel添加中划线
iOS开发小技巧 遇到的问题: 给Label添加中划线,然后并没有效果 NSString *str = [NSString stringWithFormat:@"合计金额 ¥%.2f&quo ...
- Android开发常见的Activity中内存泄漏及解决办法
上一篇文章楼主提到由Context引发的内存泄漏,在这一篇文章里,我们来谈谈Android开发中常见的Activity内存泄漏及解决办法.本文将会以“为什么”“怎么解决”的方式来介绍这几种内存泄漏. ...
- android 自定义控件View在Activity中使用findByViewId得到结果为null
转载:http://blog.csdn.net/xiabing082/article/details/48781489 1. 大家常常自定义view,,然后在xml 中添加该view 组件..如果在 ...
- activity中实现Spinner绑定
(1)须要一个基本的布局文件activity_main <RelativeLayout xmlns:android="http://schemas.android.com/apk/re ...
- 【Android】17.4 Activity与IntentService的绑定
分类:C#.Android.VS2015: 创建日期:2016-03-03 一.简介 本示例通过AlarmManager类以固定的时间间隔调用服务(每隔2秒更新一次随机生成的股票数据).如果将此示例的 ...
- Android小部件Widget开发过程中的坑和总结
@ 目录 概述 官方参考 效果图 AndroidManifest.xml Receiver Service Options res/xml/ widget_desktop_options.xml 常用 ...
随机推荐
- bzoj 2152 聪聪可可(点分治模板)
2152: 聪聪可可 Time Limit: 3 Sec Memory Limit: 259 MBSubmit: 3194 Solved: 1647[Submit][Status][Discuss ...
- python 端口扫描程序
#! /usr/bin/env python3 #-*- coding:utf-8 -*- import socket import threading OPEN_COUNT = 0 lock = t ...
- windows服务安装错误 在‘安装’过程发生异常:System.ComponentModel.Win32Exception:系统正在关机
今天安装windows服务的时候先是在本地安装测试通过,但是一到服务器就一直安装失败 在‘安装’过程发生异常:System.ComponentModel.Win32Exception:系统正在关机 然 ...
- CORS 和 JSONP
跨域资源共享(CORS) 它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制. CORS(Cross-Origin Resource Sharing) ...
- QS之force(2)
Examples 1) Force input1 to 0 at the current simulator time. force input1 0 2) Force the fourth elem ...
- JavaScript图片轮播,举一反三
图片轮播,在一些购物网站上运用的不胜枚举,下面简单介绍一下图片轮播的实现. 如图 <!doctype html> <html lang="en"> < ...
- OpenCV: 图像连通域检测的递归算法
序言:清除链接边缘,可以使用数组进行递归运算; 连通域检测的递归算法是定义级别的检测算法,且是无优化和无语义失误的. 同样可用于寻找连通域 void ClearEdge(CvMat* MM,CvPoi ...
- 【汇编】dosbox钢琴
DATA SEGMENT msg DB 0DH,0AH,'[ 1 2 3 4 5 6 7 ]' DB 0DH,0AH,' [ q w e r t y u ]' DB 0DH,0AH,'________ ...
- In Swift, typedef is called typealias:
It is used to create an alias name for another data type. The syntax of the typedef declaration is:[ ...
- js 记住我
$(function(){ $("#btn_login").click(function() { var anv=$("#an").val(); //登录名 v ...