Set up toolbar as actionbar in fragment

前端 未结 6 1756
天命终不由人
天命终不由人 2021-02-01 01:51

I want to set up my toolbar as an actionbar, but since your toolbar is a layoutelement it has to be in your layout. Now my layout is in my fragment.

I added the toolbar

相关标签:
6条回答
  • 2021-02-01 01:54

    Use

    ((ActionBarActivity) getActivity()).getSupportActionBar().setSubtitle("Your Title");
    
    0 讨论(0)
  • 2021-02-01 02:10

    ActionBar is an Activity property. If you want to set a toolbar from a given fragment as the ActionBar of the owning Activity, then get the Activity that owns the fragment (Fragment.getActivity()) and set its ActionBar property.

    Then juse use the same setDisplayHomeAsUpEnabled method you mentioned to begin with on the ActionBar after setting your toolbar as the ActionBar to get the back / up button.

    You will obviously have to manage this carefully if your app has multiple fragments within that Activity.

    0 讨论(0)
  • 2021-02-01 02:11

    Lets say the Activity holding the fragment is MainActivity.

    Do

    MainActivity main = (MainActivity)getActivity();
    //You can access all public variable and methods of MainActivity.
    //simply call 
    main.setSupportActionBar(toolbar)
    main.getSupportActionBar.setTitle("title");
    
    0 讨论(0)
  • 2021-02-01 02:13

    Now ActionBarActivity is deprecated so You need to cast your activity from getActivity() to AppCompatActivity first. Here's an example:

    ((AppCompatActivity) getActivity()).getSupportActionBar().setSubtitle();
    

    The reason you have to cast it is because getActivity() returns a FragmentActivity and you need an AppCompatActivity

    0 讨论(0)
  • 2021-02-01 02:18

    try:

     ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
    
    0 讨论(0)
  • 2021-02-01 02:18

    If you use Kotlin, try this:

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, state: Bundle?): View? { 
            (activity as AppCompatActivity).setSupportActionBar(your_toolbar)
            setHasOptionsMenu(true)
    
            return inflater.inflate(R.layout.your_layout, container, false)
    }
    
    
    override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
            inflater?.inflate(R.menu.your_menu, menu)
    }
    
    0 讨论(0)
提交回复
热议问题