【发布时间】:2018-12-19 23:40:39
【问题描述】:
我有一个Activity,其中有一个PlaceholderFragment 子类。我正在尝试将int 传递给PlaceholderFragment(这显然是有效的,我返回int 并将其打印到logcat,它确实是正确的),但是当onCreateView() 方法运行时,被传递的int突然消失并重置为0。我做错了什么?
这是我的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);
}
这里是PlaceholderFragment中int的相关声明字段、构造函数和getter/setter:
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);
编辑:SectionsPagerAdapter 是 MenuActivity 中的另一个子类。它负责获取PlaceholderFragment 的实例。这是它的全部内容:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(position + 1);
}
@Override
public int getCount() {
// Show 3 total pages.
return 3;
}
}
【问题讨论】:
标签: android variables methods subclass