Android的将数据从一个活动到他的片段(viewpager) [英] Android passing data from an activity to his fragment (viewpager)

查看:127
本文介绍了Android的将数据从一个活动到他的片段(viewpager)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个标签是碎片和ViewPager的动作条。 在MainActivity有实施LocationListener的。

I have an ActionBar with Tabs which is fragments and ViewPager. In the MainActivity there is implemented a LocationListener.

我怎么能传递位置数据从MainActivity片段?

How can I passes the location data to the fragment from the MainActivity?

MainActivity:

MainActivity:

public class MainActivity extends FragmentActivity implements ActionBar.TabListener, LocationListener{

ActionBar actionbar;
ViewPager viewpager;
FragmentPageAdapter ft;
public String str="STRING";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    viewpager = (ViewPager) findViewById(R.id.pager);
    ft = new FragmentPageAdapter(getSupportFragmentManager());

    final RunFragment fragment = (RunFragment) ft.getItem(viewpager.getCurrentItem());
    fragment.setTv(str);

    actionbar = getActionBar();
    viewpager.setAdapter(ft);
    actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    actionbar.addTab(actionbar.newTab().setText("Run").setTabListener(this));
    actionbar.addTab(actionbar.newTab().setText("Map").setTabListener(this));
    actionbar.addTab(actionbar.newTab().setText("Statistics").setTabListener(this));
    viewpager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageSelected(int arg0) {
        actionbar.setSelectedNavigationItem(arg0);

        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
            // TODO Auto-generated method stub

        }
    });


}

我想写出来的位置数据在setTv()方法,该选项卡的code:

I want to write out the location data in the setTv() method the Tab's code:

public class RunFragment extends Fragment {

public TextView tv;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.run_layout, container, false);
    tv =(TextView)view.findViewById(R.id.textView1);

    });


    return view;

}

public void setTv(String string){
    tv.setText(string);
}

}

推荐答案

您应该考虑使用事件总线库,如 Greenrobot EventBus 。有了它,你就可以从你的活动发出的事件对象在需要时和片段会接受他们,只有当它是活的。

You should consider using an event bus library, like Greenrobot EventBus. With it, you will be able to send out event objects from your activity whenever needed and the Fragment will receive them only when it is alive.

这篇关于Android的将数据从一个活动到他的片段(viewpager)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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