无法将数据从活动发送到片段

时间:2019-02-22 21:49:53

标签: android android-fragments android-activity

我已经尝试了Internet上几乎所有的解决方案来解决我的问题,但是没有运气!

我有一个名为TimeTableActivity的活动:

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

    mSectionsPageAdapter = new SectionsPageAdapter(getSupportFragmentManager());

    mViewPager = (ViewPager) findViewById(R.id.container);
    setupViewPager(mViewPager);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

    Bundle extras = getIntent().getExtras();
    String stationTitle = extras.getString("stationTitle");
    int stationID = extras.getInt("stationID");
}

我想将此“ stationID”发送到片段。

1 个答案:

答案 0 :(得分:0)

尝试下面的代码将{station1} int从activity传递到fragment

YourActivity类:

private static FragmentManager fragmentManager;

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

    fragmentManager = getSupportFragmentManager();//Get Fragment Manager


    //Place below code where you want to send stationID.

    YourFragment frag = new YourFragment();//Get Fragment Instance
    Bundle data = new Bundle();//Use bundle to pass data
    data.putString("stationID", stationID);//put string, int, etc in bundle with a key value
    frag.setArguments(data);//Finally set argument bundle to fragment
    fragmentManager.beginTransaction().replace(R.id.fragmentContainer, frag).commit();//now replace the argument fragment               
}

YourFragment类:

public class YourFragment extends Fragment {
    public YourFragment() {
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragmentlayout, container, false);//Inflate Layout

        //Get Argument that passed from activity in "stationID" key value
        int getstationID = getArguments().getString("stationID");
        return view;//return view
    }
}