Android:在片段之间传递对象 [英] Android: Passing Objects Between Fragments

查看:114
本文介绍了Android:在片段之间传递对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我开始之前,我先浏览了以下问题:

Before i start, i have look through question such as:

在片段之间传递数据:屏幕重叠 如何在片段之间传递值

以及Android文档:

as well as Android docs:

http://developer.android.com/training/basics/fragments/communicating.html

以及本文:

http://manishkpr.webheavens.com/android-passing-片段之间的数据/

尽管上面提到的所有情况都与我的情况相似,但并不完全相同.我在这里遵循了一个不错的教程(我的代码的某些部分基于本文):

Though all the cases mentioned above similar to what i have, it is not entirely identical. I followed a good tutorial here (Some portion of my code is based on this article):

http://www. androidhive.info/2013/10/android-tab-layout-with-swipeable-views-1/

我有以下文件:

RegisterActivity.java
NonSwipeableViewPager.java
ScreenSliderAdapter.java
RegisterOneFragment.java
RegisterTwoFragment.java

RegisterActivity.java
NonSwipeableViewPager.java
ScreenSliderAdapter.java
RegisterOneFragment.java
RegisterTwoFragment.java

以及以下布局:

activity_register.xml
fragment_register_one.xml
fragment_register_two.xml

activity_register.xml
fragment_register_one.xml
fragment_register_two.xml

我想要实现的是将一个Serializable对象从RegisterFragmentOne传递到RegisterFragmentTwo.

What i am trying to achieve is passing an Serializable object from RegisterFragmentOne to RegisterFragmentTwo.

到目前为止,这是我所做的(省略了一些代码):

So far this is what i have done (some codes are omitted):

RegisterActivity.java

public class RegisterActivity extends FragmentActivity
             implements RegisterOneFragment.OnEmailRegisteredListener{

    public static NonSwipeableViewPager viewPager;
    private ScreenSliderAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        // Initilization
        mAdapter = new ScreenSliderAdapter(getSupportFragmentManager());
        viewPager = (NonSwipeableViewPager) findViewById(R.id.pager);
        viewPager.setAdapter(mAdapter);
    }

    public void onEmailRegistered(int position, Registration regData){
        Bundle args = new Bundle();
        args.putSerializable("regData", regData);
        viewPager.setCurrentItem(position, true);
    }
}

ScreenSliderAdapter.java

public class ScreenSliderAdapter extends FragmentPagerAdapter{

    public ScreenSliderAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int index) {

        switch (index) {
        case 0:
            return new RegisterOneFragment();
        case 1:
            return new RegisterTwoFragment();
        case 2:
            return new RegisterThreeFragment();
        }

        return null;
    }

    @Override
    public int getCount() {
        return 3;
    }
}

NonSwipeableViewPager.java (扩展ViewPager类,并覆盖以下内容)

NonSwipeableViewPager.java (extending ViewPager class, and overrides the following)

@Override
public boolean onInterceptTouchEvent(MotionEvent arg0) {
    // Never allow swiping to switch between pages
    return false;
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    // Never allow swiping to switch between pages
    return false;
}

RegisterOneFragment.java

public class RegisterOneFragment extends Fragment {
    OnEmailRegisteredListener mCallBack;
    public interface OnEmailRegisteredListener {
        /** Called by RegisterOneFragment when an email is registered */
        public void onEmailRegistered(int position, Registration regData);
    }

public void onAttach(Activity activity){
    super.onAttach(activity);

    // This makes sure that the container activity has implemented
    // the callback interface. If not, it throws an exception.
    try {
        mCallBack = (OnEmailRegisteredListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnEmailRegisteredListener");
    }
}

... And some to execute some HTTP request via separate thread...
}

我要完成的工作是,只要用户按下RegisterOneFragment上的按钮,数据就会发送到服务器(并通过JSON返回一些验证).如果返回的数据有效,则应用程序应转到下一个片段,即RegistrationTwoFragment.

What i am trying to accomplish is that when ever a user pressed a button on RegisterOneFragment, a data will be sent to a server (and returns some validation over JSON). If the returned data is valid, the the application should go to the next fragment which is RegistrationTwoFragment.

我对如何在片段之间传递对象感到有些困惑,因为我的片段是使用适配器创建的.然后将该适配器附加到我的活动中.

I am having some confusion as how to pass objects between fragments, since my Fragments is created using an Adapter. And that Adapter is then attached to my Activity.

有人可以帮我吗?谢谢

我试图像这样制作一个快捷方式(不幸的是不起作用):

I tried to make a shortcut (unfortunately does not work) like so:

在我创建的RegisterActivity中:

In RegisterActivity i created:

public Registration regData;

并在RegisterOneFragment中:

and in RegisterOneFragment:

/* PLACED ON POST EXECUTE */
((RegisterActivity)getActivity()).regData = regData;

最后在Re​​gisterTwoFragment中调用了它

Finally called it in RegisterTwoFragment

Registration regData;
regData = ((RegisterActivity) getActivity()).regData;

它抛出一个nullPointerExceptions

It throws a nullPointerExceptions

编辑2

需要明确的是,RegisterActivty包含多个片段.用户唯一可在片段之间导航的方法是单击按钮.该活动没有选项卡栏.

Just to be clear, RegisterActivty contains multiple fragments. And the only way user can navigate between fragment is by clicking a button. The Activity has no Tab bar.

推荐答案

在包含活动中,我通常会具有与此类似的设置器或方法.

I would normally have setters or methods similar to this in the containing activity.

因此,如果我理解正确,您希望用户访问RegistrationOneFragment,然后在完成后使用此数据并对其进行验证,如果有效,请将其传递给RegistrationTwoFragment并将用户移至该Fragment

So if I understand correctly, you want the user to access RegistrationOneFragment, then when completed, use this data, validate it, and if valid, pass it along to RegistrationTwoFragment and move the user to this Fragment.

您能否简单地在onEmailRegistered方法中调用validateJson(regData)来处理活动中的验证,如果验证成功,则向RegistrationTwoFragment提交事务.

Could you simply call validateJson(regData) in your onEmailRegistered method to handle the validation in your activity, if it succeeds, commit a transaction to RegistrationTwoFragment.

那么您所需要的就是活动或片段中的获取器和设置器,以在活动中或片段中的setData(Registration args)中说出getRegistrationOneData(),如上面的示例所示.

Then all you need are getters and setters in your activity or Fragment to say getRegistrationOneData() in the activity or setData(Registration args) in the fragment as your examples show above.

我不知道将args直接传递到Fragment中的任何方法.

I don't know of any way to pass the args directly into the Fragment.

这篇关于Android:在片段之间传递对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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