在Activity按钮点击事件中获取Fragments EditText的值

3
我有一个包含2个片段的视图页面(ViewPager),每个片段都包含一个编辑框(edittext)。当用户在活动(activity)中点击按钮时,我需要获取片段中编辑框的值并传递到活动中。我参考了这篇文档 与其他片段通信,它类似于当用户在片段中点击列表项时,我将在活动中获取值。但在我的情况下,按钮在活动中。有人能建议正确的做法吗?
2个回答

5

你可以像Christopher Francisco建议的那样(使用TextWatchers),或者你可以给EditText分配ID,并像这样检索它们的数据(在Activity中的Buttons onClickListener内):

String editText1Data = ((EditText) findViewById(R.id.editText1)).getText().toString();
String editText2Data = ((EditText) findViewById(R.id.editText2)).getText().toString();
....

我搜索了很多次,所有的解决方案都是使用观察器和监听器!你的答案更加简单明了!为什么其他人要使用那种方法?它有什么好处吗? - Hasan Shouman
非常好的答案!!正是我在寻找的 :) - Ali_Waris
非常感谢。 - shariful islam

2

不要让ActivityFragment请求数据,而是从Fragment传递数据到Activity(无需请求)。

我的意思是,在EditText中添加TextWatcher接口,并使用afterTextChanged()接口(请再次阅读http://developer.android.com/training/basics/fragments/communicating.html)将其传递给Activity。 当用户按下按钮时,您不必从片段中检索值,因为您已经拥有它们,您只需要应用逻辑即可。

例如:

// 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);
}    

感谢您的及时回复,Christopher。我对您的帖子有疑问。如果我有更多的输入控件,比如3到4个EditText和1到2个选择器等,我该如何扩展它?将更改事件放置在各个控件上的上述逻辑是否是实现它的正确方式? - Maghesh
实际上,我的做法是在onFragment1EditTextChange()方法中放置尽可能多的参数(显然,使用不同的名称哈哈哈),以便输入视图在我的片段中。 - Christopher Francisco
如果您觉得我的帖子有帮助,您可能想考虑将其标记为被接受的答案,这样其他人就能知道您是如何解决问题的 (: - Christopher Francisco
抱歉回复晚了,我无法从您的评论中清楚地理解,请您能否给我提供一个示例或详细说明一下。 - Maghesh
非常好的和非常有用的答案 :) 比原始文档更好的解释。 - uniruddh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接