将对象从活动传递到片段

时间:2016-03-13 07:06:30

标签: android android-fragments android-fragmentactivity android-tablayout

我是Android的新手。这是我的第一个应用程序。我尝试在Internet上搜索但是每个人都试图将简单数据从活动传递到片段。我想将整个对象从活动传递到片段。 我知道有一个解决方案就是使用serialize&反序列化&将数据放入Bundle。

而是尝试序列化&反序列化,我在我的活动中创建了一个非静态方法。试图在片段和放大器中获取getActivity()然后调用该方法,但它返回null。任何人都可以帮助我解决我的错误。

以下是我的代码: -

BaseDefaultActivity是我自己的自定义类,它扩展了AppCompatActivity。

public class EventDetailActivity extends BaseDefaultActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setBaseContentView(R.layout.activity_event_detail);
        ButterKnife.bind(this);
        initialiseDataFromIntend();
        DummyObject obj=new DummyObj();
        setDataObject(obj);

        // Get the ViewPager and set it's PagerAdapter so that it can display items
        viewPager.setAdapter(new EventDetailFragementAdapter(getSupportFragmentManager(), EventDetailActivity.this));

        // Give the TabLayout the ViewPager
        tabLayout.setupWithViewPager(viewPager);
    }

}


public class BaseDefaultActivity extends AppCompatActivity implements BaseActivity {
    private Object dataObj;
    public void setDataObject(Object obj) {
            this.dataObj = obj;
        }

        public Object getDataObj() {
            return this.dataObj;
        }
    }



public class EventDetailFragementAdapter extends FragmentPagerAdapter {
    final int PAGE_COUNT = 3;
    private String tabTitles[] = new String[]{"Tab1", "Tab2", "Tab3"};
    private Context context;

    public EventDetailFragementAdapter(FragmentManager fm, Context context) {
        super(fm);
        this.context = context;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return tabTitles[position];
    }

    @Override
    public Fragment getItem(int position) {
        Fragment fragment = null;
        switch (position) {
            case 0:
                fragment = new EventDetailFragement();
                break;

            case 1:
                fragment = new EventBasicInfoFragement();
                break;

            default:
                fragment = new EventDetailFragement();
                break;
        }
        return fragment;
    }


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



public class EventDetailFragement extends Fragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.event_detail_fragement, container, false);
        TextView textView = (TextView) view;
        textView.setText("AAAAAAA #" + (SearchEventResponseObject) ((BaseDefaultActivity) getActivity()).getDataObj());
        return view;
    }
}

0 个答案:

没有答案