我有一个Activity
,其中有一个PlaceholderFragment
子类。我正在尝试将int
传递到PlaceholderFragment
(显然可以,我返回了int
并将其打印到logcat,这确实是正确的),但是当{ {1}}方法运行后,通过的onCreateView()
突然消失并重置为0。我在做什么错了?
这是我的int
中负责传递Activity
的代码:
int
以下是public void setActivityTitle(){
toolbar = findViewById(R.id.toolbar);
resName = getIntent().getExtras().getString("Name");
this.ResID = getIntent().getExtras().getInt("ResID");
PlaceholderFragment pf = new PlaceholderFragment(ResID);
//↑ I know that PlaceholderFragments should almost always have default constructors, but I was desperate. The default empty constructor is still there though
pf.receiveResID(ResID);
//↑ This method is basically a setter for the ResID int
Log.e("SplitBill","ResID that we got from PlaceholderFragment is " + pf.getResID());
//↑ This output is as expected, and matches the int that I pass down
toolbar.setTitle(resName);
}
中int
的相关声明字段,构造函数和getter / setter:
PlaceholderFragment
这是我的 private int ResID;
public PlaceholderFragment() {
}
public PlaceholderFragment(int resID) {
this.ResID = resID;
Log.e("SplitBill","PlaceholderFragment: Received ResID as " + ResID);
//↑ This returns the correct int to logcat
}
public int getResID() {
return ResID;
//Outside the subclass, this returns the correct int. Inside it, this returns 0
}
public void receiveResID(int ResID) {
this.ResID = ResID;
Log.e("SplitBill","PlaceholderFragment: Received ResID as " + ResID);
//↑ This also works as expected
}
的一部分,应该在数据库查询中使用onCreaeView()
:
int
编辑: @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_menu, container, false);
MenuViewModel viewModel = ViewModelProviders.of(this).get(MenuViewModel.class);
//MenuActivity m = new MenuActivity();
//int resID = m.getResID();
//↑ This was my attempt at trying to get the int straight from a getter in the MenuActivity, it returns 0
Log.e("SplitBill","From onCreateView(): ResID is " + ResID);
//↑ This also prints 0 to logcat
viewModel.setResID(ResID);
是MenuActivity中的另一个子类。它负责获取SectionsPagerAdapter
的实例。这是全部内容:
PlaceholderFragment
答案 0 :(得分:1)
您只能将空构造函数与Fragments一起使用。
public static MyFragment newInstance(int someInt) {
MyFragment myFragment = new MyFragment();
Bundle args = new Bundle();
args.putInt("someInt", someInt);
myFragment.setArguments(args);
return myFragment;
}
MyFragment fragment = MyFragment.newInstance(5);
是获取片段实例并设置值的方式。
要获取价值,请使用getArguments().getInt("someInt", 0);
片段方法内的onCreate()