在 MainActivity 和 Fragment 之间通信

Communicate between MainActivity and a Fragment

你好 Whosebug 社区,我看了很多示例,但我无法将其应用到我的代码中。所以我有以下代码:

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;
    }
}

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

提前致谢:)

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

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 模式。