获得的数据片段对话框后面 - 最佳做法? [英] Get data back from a fragment dialog - best practices?

查看:118
本文介绍了获得的数据片段对话框后面 - 最佳做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将我的一些项目中使用的片段。我们如何用一个片段对话沟通?我想创建一个片段对话只是为了得到一些来自用户的文本输入。当被驳回的对话,我想通过输入的文本回到母片段(启动它的一个)。例如:

I'm converting some of my project to use fragments. How do we communicate with a fragment dialog? I want to create a fragment dialog just to get some text input from the user. When the dialog is dismissed, I'd like to pass the entered text back to the "parent" fragment (the one that started it). Example:

public class MyFragment extends Fragment {

    public void onBtnClick() {
        // What's a good way to get data back from this dialog 
        // once it's dismissed?
        DialogFragment dlgFrag = MyFragmentDialog.newInstance();
        dlgFrag.show(getFragmentManager(), "dialog"); 
    }
}

感谢

推荐答案

一个伟大的方式来传递这样的事件是一个回调接口像descripted的Andr​​oid开发者指南中

A great way to pass this kind of Events is a Callback Interface like descripted in the Android Developers Guide

您片段定义一个回调接口,如

Your Fragment define a Callback Interface like

public class MyFragment extends Fragment {
    ...
    // Container Activity must implement this interface
    public interface OnArticleSelectedListener {
        public void onArticleSelected(Uri articleUri);
    }
    ...
}

然后检查里面的onAttach法如果家长实施的回调接口,并保存实例。

Then you check inside your onAttach Method if the Parent implemented the Callback Interface and save the Instance.

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        mListener = (OnArticleSelectedListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString() + " must implement OnArticleSelectedListener");
    }
}

当你的事件片段内发生了,你只需调用回调处理

when your Event inside the Fragment happens you simply call the Callback Handler

mListener.onArticleSelected(...);

希望帮助,进一步的相关信息<一个href="http://developer.android.com/guide/topics/fundamentals/fragments.html#CommunicatingWithActivity">here

这篇关于获得的数据片段对话框后面 - 最佳做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆