在MainActivity和Fragment之间进行通信

时间:2017-11-15 21:41:22

标签: java android android-activity fragment communication

Hello Stackoverflow社区,我看了很多例子,但我不能将它应用到我的代码中。所以我有以下代码:

public class Profile extends AppCompatActivity {

private ViewPager mPager_profile;
private static final int NUM_PAGES = 3;
private PagerAdapter mPagerAdapter_profile;



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

    // set up the slider
    mPager_profile = (ViewPager) findViewById(R.id.pager_profile);
    mPagerAdapter_profile = new ScreenSlidePagerAdapter_profile(getSupportFragmentManager());
    mPager_profile.setAdapter(mPagerAdapter_profile);
    // bottom dots
    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout_profile);
    tabLayout.setupWithViewPager(mPager_profile, true);

    Intent intent = getIntent();
    String[] data = intent.getStringArrayExtra("data");

}

// some code here
...

private class ScreenSlidePagerAdapter_profile extends 
FragmentStatePagerAdapter {
    public ScreenSlidePagerAdapter_profile(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        switch (position){
            case 0:
                return new event_slide();
            case 1:
                return new profile_slide();
            case 2:
                return new option_slide();
            default:
                return null;

        }
    }

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

}

以下代码是我的event_slide.java片段:

public class event_slide extends android.support.v4.app.Fragment{

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstance){
        ViewGroup eventView = (ViewGroup)inflater.inflate(R.layout.login_event, container, false);

        return eventView;
    }
}

我的问题是:如何传递名为"数据"的字符串数组?到我的Fragment event_slide,然后将示例(String - >)data [0]应用于其中一个TextView,例如findViewById(R.id.textView9).setText(data [0])。我是Android开发的新手,所以请保持简单。

提前致谢:)

1 个答案:

答案 0 :(得分:0)

最简单的方法是(但不是最好的方式):

public class EventSlide extends android.support.v4.app.Fragment{

    public String arg1;

    public EventSlide(String arg1){
        this.arg1 = arg1;
    }

    // Override OnCreate method, initialize your textView and set your text there
}

我建议你看看newInstance模式。