如何使用Intents和bundle传递值

时间:2016-10-28 10:50:27

标签: java android android-studio android-fragments android-activity

我正在尝试将Activity中的值传递给Fragment,但Bundle始终为空。

活动

CallLogsFragment callLogfrag = new CallLogsFragment();
Intent intent = new Intent(this, DeviceUsageActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("key", callgroup);
callLogfrag.setArguments(bundle);
this.startActivity(intent);

旨在从Activity

中检索价值的片段
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    bundle = this.getArguments();
    if (bundle != null) {
        int myInt = bundle.getInt("key", 0);
    }
    View view = inflater.inflate(R.layout.fragment_call_logs, container, false);
    load(view);
    setupList(view);

    return view;
}

3 个答案:

答案 0 :(得分:1)

尝试这个

 // send value from activity to fragment 

CallLogsFragment callLogfrag = new CallLogsFragment();
Bundle bundle = new Bundle();
bundle.putInt("key", "4");
callLogfrag.setArguments(bundle);
 // call fragment from activity
getSupportFragmentManager().beginTransaction().replace(R.id.containar, callLogfrag).commit();

//  get value in fragment 

    if (getArguments() != null) {
        int status = getArguments().getInt("key");

答案 1 :(得分:0)

如果我清楚你的问题!!您正尝试将数据从一个活动发送到另一个活动中的片段。

然后,您需要先在Intent中发送启动第二个活动的数据。然后从intent获取数据并将数据设置为fragment作为参数,并将片段添加到父活动。

//here you go, from first activity
Intent intent = new Intent(this, DeviceUsageActivity.class);
 Bundle bundle = new Bundle();
bundle.putInt("key", callgroup);
intent.putExtra("yourdata",bundle);
//start your activity - parent activity of your fragment
this.startActivity(intent);

//then get your data in DeviceUsageActivity in onCreate()
 Bundle yourdata = null;
if(getIntent().getExtras() != null) {
       yourdata = getIntent().getBundleExtra("yourdata");
}

//Then sent data to fragment
CallLogsFragment callLogfrag = new CallLogsFragment();

callLogfrag.setArguments(yourdata);
 // add fragment to parent activity
getSupportFragmentManager().beginTransaction().replace(R.id.containar, callLogfrag).commit();

//rest you know - get bundle argument in fragmet

答案 2 :(得分:-1)

从活动到商店数据

Intent i = new Intent(getApplicationContext(), NewActivity.class);

    i.putExtra("key","value");
    startActivity(i);

要将数据检索回片段,请仅在片段

中使用Context作为getActivity
Bundle extras = getIntent().getExtras();
if (extras != null) {
    String value = extras.getString("key");
    //The key argument here must match that used in the other activity
}