我需要在片段中使用setSupportActionBar,我无法也无法使用setContentView请帮助它也提前谢谢你 给出相关代码
public class StudentrFragment extends Fragment {
Toolbar toolbar;
TabLayout tabLayout;
ViewPager viewPager;
ViewPagerAdapter viewPagerAdapter;
public StudentrFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.tabbar_layout);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
viewPager = (ViewPager) findViewById(R.id.viewPager);
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPagerAdapter.addFragments(new CivilFragment(),"Civil Dept");
viewPagerAdapter.addFragments(new ComputerFragment(),"CSE Dept");
viewPagerAdapter.addFragments(new EeeFragment(),"EEE Dept");
viewPagerAdapter.addFragments(new EceFragment(),"ECE Dept");
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
}
}
答案 0 :(得分:97)
你可以在片段中设置这样的SupportActionbar:
((AppCompatActivity)getActivity()).setSupportActionBar(mToolbar);
您需要tabbar_layout
onCreateView
Fragment
中的@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tabbar_layout, container, false);
//YOUR STUFF
return rootView;
}
。
像这样:
xargs git log --decorate --no-walk=unsorted --oneline < .git/MERGE_HEAD
答案 1 :(得分:0)
suggested solution可以工作,但是看起来并不优雅,理想情况下,片段应该不了解其父活动。另一种选择是根本不使用setSupportActionBar。如果您使用navigation库,则将Toolbar添加到片段布局并使用NavigationUI进行设置可能会更容易,例如:
<!-- my_fragment.xml -->
<androidx.constraintlayout.widget.ConstraintLayout ... >
<com.google.android.material.appbar.MaterialToolbar
android:id="@+id/toolbar"
... />
</androidx.constraintlayout.widget.ConstraintLayout>
class MyFragment : Fragment() {
...
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val navController = findNavController()
binding.toolbar.setupWithNavController(navController)
}
}
您可以找到完整的GitHub示例here。另外,请查看另一个问题Is setSupportActionbar required anymore?和我的answer,以了解更多详细信息。
答案 2 :(得分:0)
This site has the solution which worked for me!
粘贴:
toolbar = (Toolbar) getView().findViewById(R.id.toolbar);
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(toolbar);