从 ViewPager 获取不同片段的值

Getting the values from the different fragments from ViewPager(从 ViewPager 获取不同片段的值)

本文介绍了从 ViewPager 获取不同片段的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个动态生成片段的应用程序.

I am developing an application where the fragments are being generated dynamically.

private void setupViewPager(ViewPager viewPager) {
    adapter = new ViewPagerAdapter(getSupportFragmentManager());
    for (int i = 0; i < sequence_no.size(); i++) 
    {
        adapter.addFragment(FragmentTwo.newInstance(i,(i+1)));
    }
    viewPager.setAdapter(adapter);
}

现在假设确实生成了三个片段.生成的片段确实有不同的小部件,如编辑文本、微调器等.我会管理它,因为我有一个标志通知我要显示哪一个(微调器或编辑文本).

Now suppose there does three fragments got generated. The generated fragments do have different widgets like edittext, spinner etc. which i do mannage as i have one flag which notifies me which one to be displayed(spinner or edittext).

我有一个活动按钮,单击该按钮后我需要从所有片段中获取值,但我如何仅从第一个片段中获取值.

I have one button in activity upon whose click i need to get the values from all the fragments bu some how I am getting the value from first fragment only.

我在这里放了一个错误的样本,因为我知道它是错误的,但我保留以供参考.

I am putting a wrong sample over here as I know its wrong but I am keeping for reference purpose.

下面是提交按钮单击的代码,其中值是一个数组列表.

below is the code on submit button click where values is an array list.

if (FragmentTwo.ed_complain != null) 
    {
        values.add(FragmentTwo.ed_complain.getText().toString());
    }
    if (FragmentTwo.cb_complain != null) 
    {
        values.add(FragmentTwo.cb_complain.getText().toString());
    }
    if (FragmentTwo.spinner_complain != null && FragmentTwo.spinner_complain.getSelectedItem() != null) 
    {
        values.add(FragmentTwo.spinner_complain.getSelectedItem().toString());
    }

请建议我如何从所有片段中获取所有值.

Please suggest me what I need to do for fetching all the values from all the fragments.

推荐答案

你可以用这种方式解决这个问题.创建一个 Interface 并在每个片段中实现它.现在使用这个 Interface 你可以从特定的片段中获取价值.

You can solve this problem using this way. Create an Interface and implement it in each fragments. Now using this Interface you can get value from specific fragment.

例如,您创建一个 Interface

public interface IGetValue{
String getEditTextValue();
}

现在,如果每个 Fragment 都实现了这个接口,那么每个 Fragment 都必须实现这个 getEditTextValue() 方法,您可以返回该实现方法的 EditText 值.只需使用:

Now, if each Fragment implements this interface then each fragment have to implements this getEditTextValue() method and you can return EditText value of that implemented method. just use :

@Override
public String getEditTextValue() {

    return YOUR_EDIT_TEXT.getText().toString();
}

现在,如果您想在活动中从 Fragment1 获取 EditText 值,只需使用以下代码行:

Now, if you want to get EditText value from Fragment1 in your activity, just use this line of code:

String valueFromFragment1= fragment1Instance.getEditTextValue();

有关详细信息,请查看 this 和 这个答案.

For more info, check this and this answer.

谢谢:)

这篇关于从 ViewPager 获取不同片段的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:从 ViewPager 获取不同片段的值

基础教程推荐