好的,所以我在ViewPager中有一个Fragment,我正尝试使用数据库中的onCreateView()
在Fragment的LiveData
中设置ViewPager的选项卡。我期望发生的事情是改变选项卡,发生的事情是……什么都没有。我要去哪里错了?
这里是onCreateView()
:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_menu, container, false);
final MenuActivity menuAct = (MenuActivity) getActivity();
final MenuViewModel viewModel = ViewModelProviders.of(this, new MenuViewModelFactory(menuAct.getApplication(), MenuActivity.ResID)).get(MenuViewModel.class);
final Fragment f = this;
viewModel.getAllMenuTitles().observe(this, new Observer<String[]>() {
@Override
public void onChanged(String[] strings) {
final Spinner spinner = rootView.findViewById(R.id.spinner);
final SubMenuViewModel subMenuViewModel = ViewModelProviders.of(f, new SubMenuViewModelFactory(menuAct.getApplication(), spinner.getSelectedItemPosition() + 1)).get(SubMenuViewModel.class);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), R.layout.support_simple_spinner_dropdown_item, strings);
adapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
menuAct.removeAllTabs();
subMenuViewModel.getSubMenus().observe(f.getActivity(), new Observer<String[]>() {
@Override
public void onChanged(@Nullable String[] strings) {
menuAct.populateTabs(strings);
}
});
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
});
return rootView;
}
这里是removeAllTabs()
:
public void removeAllTabs() {
int cnp = mViewPager.getChildCount();
while (cnp > 1) {
mSectionsPagerAdapter.destroyItem(mViewPager, cnp - 1, mSectionsPagerAdapter.getItem(cnp - 1));
mTabLayout.removeTabAt(cnp - 1);
cnp--;
}
mSectionsPagerAdapter.notifyDataSetChanged();
}
这是populateTabs()
:
public void populateTabs(String[] subMenus) {
for (int i = 0; i < subMenus.length; i++) {
mTabLayout.addTab(mTabLayout.newTab().setText(subMenus[i]),i);
Log.d(TAG, "Added " + (subMenus[i]) + " to TabLayout");
}
mTabLayout.invalidate();
mSectionsPagerAdapter.notifyDataSetChanged();
}
似乎populateTabs()
根本没有运行。