如何将参数传递给片段?

时间:2018-07-17 15:48:53

标签: android android-fragments viewmodel

好的,所以我在一个活动中有一个片段。我试图将启动活动的意图的int传递给该片段,但是由于某种原因,我从该片段的参数中获取了0。我在做什么错了?

这是负责将int传递过来的代码:

public void initActivity() {
    toolbar = findViewById(R.id.toolbar);

    resName = getIntent().getExtras().getString("Name");
    int ResID = getIntent().getExtras().getInt("ResID");
    Log.d("SplitBill","From initActivity(): We have received ResID as " + ResID);

    Bundle bundle = new Bundle();
    bundle.putInt("ResID", ResID);
    Log.d("SplitBill",bundle.getInt("ResID") + " has been put into the bundle.");

    PlaceholderFragment pf = new PlaceholderFragment();
    pf.setArguments(bundle);

    toolbar.setTitle(resName);
}

这是负责接收int的代码:

Activity activity = getActivity();
Bundle args = getArguments();
MenuViewModel viewModel = ViewModelProviders.of(this, new MenuViewModelFactory(activity.getApplication(), args.getInt(“ResID”))).get(MenuViewModel.class);

如果我在上面的args.getInt()上面的地方手动输入一个数字,该代码就可以正常工作,我只是在努力从上面设置的参数中获取整数。

很抱歉,格式错误,我在手机上输入了此内容。

MenuActivity中的ResID声明:private int ResID;

2 个答案:

答案 0 :(得分:0)

发件人:@Override onCreate()中的Activity类。

接收器:@Override onCreateView()中的片段类。

Android lifecycle diagram for Activity and Fragment.

Android documentation for Bundle.

public class MyApplication extends AppCompatActivity {
 @Override onCreate(...){
  Bundle bundle = new Bundle();
  bundle.putInteger("myint", YOUR_INT_GOES_HERE);
  this.setArguments(bundle);

  //see your int and make sure it's inside the bundle.
  Log.d("onCreate()", "my sender : " + YOUR_INT_GOES_HERE 
  + " what i'm sending: " + bundle.getString("myint") );
 }
}
public class MyFragmentExtension extends Fragment {
 @Override onCreateView(...){
  int receiver = getArguments().getString("myint");
  Log.d("onCreateView()", "my receiver: " + receiver);
 }
}

答案 1 :(得分:0)

解决了!由于在Bundle中传递int根本不起作用(请参阅@EvOlaNdLuPiZ答案和注释线程),因此我在类顶部将其声明为public static int,并使用{片段的onCreateView()方法中的{1}}。感谢您的所有帮助!