获取碎片上的活动按钮点击事件的EditText值 [英] Get Fragments edittext values on Activity button click event

查看:473
本文介绍了获取碎片上的活动按钮点击事件的EditText值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含2片一viewpager,每个片段包含的EditText。当用户点击这个按钮的活动,我需要得到的片段活动的EditText值。我提到了这个文档沟通与其它片段的,这是一样的东西时,用户点击该片段中的列表项,我会得到我的情况下,在activity.But的值按钮在activity.Could有人提出这样做​​的正确方法

I have a viewpager containing 2 fragments and each fragment contains a edittext. When user clicks the button in the activity i need to get the edittext values in the fragments to activity. I referred to this documentation Communicating with Other Fragments, it is something like when user click the list item within the fragment i will get the values in the activity.But in my case the button is in activity.Could anyone suggest the right way of doing this

推荐答案

相反,活动询问的片段数据,从片段活动(没有它的必要问)。

Instead of the Activity asking the Fragment for data, pass data from Fragment to Activity (without the need of it to ask).

我的意思是,添加一个 TextWatcher 接口的EditText afterTextChanged( )使用接口​​(读取再次的http://开发商.android.com /培训/基础知识/片段/ communicating.html )将其传递给活动。当用户preSS的按钮,你不必检索碎片的价值,因为你已经有了他们,你只需要应用逻辑。

What I mean is, add a TextWatcher interface to the EditText and afterTextChanged() use an interface (read again http://developer.android.com/training/basics/fragments/communicating.html) to pass it to the Activity. When the user press the button, you dont have to retrieve the value from the fragments, cause you already have them, you just have to apply the logic.

例如:

// Inside Activity, it should implement FragmentInterface1, FragmentInterface2
private String str1;
private String str2

@Override
public void onFragment1EditTextChanged(String string) {
    str1 = string;
}

@Override
public void onFragment2EditTextChanged(String string) {
    str2 = string;
}

// This is for each Fragment1 and Fragment2, just change the number acordingly
private FragmentInterface1 listener = null;

@Override
public View onCreateView(/*params*/) {

    // inflate the view

    edittext = (EditText) view.findViewById(R.id.myEditText);
    edittext.addTextWatcher(new TextWatcher() {

        // Any callback works, but i'd go for this one
        public void afterTextChanged(/*params*/) {
            if(listener != null) listener.onFragment1EditTextChanged(edittext.getText().toString());
        }
    });
}

@Override
public void onAttach(Activity activity) {
    listener = (FragmentInterface1) activity;
}

public interface FragmentInterface1 {
    public void onFragment1EditTextChanged(String string);
}    

这篇关于获取碎片上的活动按钮点击事件的EditText值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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