请如何在最新版本的Android Studio 3.5中将“选项卡式活动”添加到导航抽屉片段中。我遇到“无法通过findViewById和getSupportFragmentManager解析方法”的问题。我需要导入什么,正在使用最新版本和androidx。而且,如果我将实现FragmentActivity或任何其他活动添加到类中,它将关闭应用程序并引发异常。
公共类SendMoneyFragment扩展Fragment {
private SendMoneyViewModel toolsViewModel;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
toolsViewModel =
ViewModelProviders.of(this).get(SendMoneyViewModel.class);
View root = inflater.inflate(R.layout.fragment_sendmoney, container, false);
final TextView textView = root.findViewById(R.id.text_sendmoney);
toolsViewModel.getText().observe(this, new Observer<String>() {
@Override
public void onChanged(@Nullable String s) {
textView.setText(s);
}
});
return root;
//setupViewPager();
//method two
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
TabsAdapter adapter = new TabsAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.main_tabs);
tabLayout.setupWithViewPager(viewPager);
}
最佳答案
解决方案可以完美地工作:
公共类SendMoneyFragment扩展Fragment {
ViewPager pager;
private SendMoneyViewModel toolsViewModel;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
toolsViewModel = ViewModelProviders.of(this).get(SendMoneyViewModel.class);
View root = inflater.inflate(R.layout.fragment_sendmoney, container, false);
final TextView textView = root.findViewById(R.id.text_sendmoney);
TabLayout tabs = (TabLayout) root.findViewById(R.id.main_tabs);
pager=(ViewPager) root.findViewById(R.id.pager);
ViewPagerAdapter adapter = new ViewPagerAdapter(getFragmentManager());
adapter.addFragment(new MoneyAccount(), "Send To Accounts");
adapter.addFragment(new MoneyAgents(), "Send To Agents");
adapter.addFragment(new MoneyBanks(), "Send To Banks");
pager.setAdapter(adapter);
tabs.setupWithViewPager(pager);
toolsViewModel.getText().observe(this, new Observer<String>() {
@Override
public void onChanged(@Nullable String s) {
textView.setText(s);
}
});
return root;
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mList = new ArrayList<>();
private final List<String> mTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager supportFragmentManager) {
super(supportFragmentManager);
}
@Override
public Fragment getItem(int i) {
return mList.get(i);
}
@Override
public int getCount() {
return mList.size();
}
public void addFragment(Fragment fragment, String title) {
mList.add(fragment);
mTitleList.add(title);
}
@Override
public CharSequence getPageTitle(int position) {
return mTitleList.get(position);
}
}