How to get Toolbar from fragment?
You have two choices to get Toolbar in fragment
First one
Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
and second one
Toolbar toolbar = ((MainActivity) getActivity()).mToolbar;
toolbar = (Toolbar) getView().findViewById(R.id.toolbar);
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(toolbar);
You need to cast your activity from getActivity()
to AppCompatActivity
first. Here's an example:
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle();
The reason you have to cast it is because getActivity()
returns a FragmentActivity
and you need an AppCompatActivity
In Kotlin:
(activity as AppCompatActivity).supportActionBar?.title = "My Title"
In case fragments should have custom view of ToolBar you can implement ToolBar for each fragment separately.
add ToolBar into fragment_layout:
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimaryDark"/>
find it in fragment:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment, container, false);
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
//set toolbar appearance
toolbar.setBackground(R.color.material_blue_grey_800);
//for crate home button
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(toolbar);
activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
menu listener could be created two ways: override onOptionsItemSelected in your fragment:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case android.R.id.home:
getActivity().onBackPressed();
}
return super.onOptionsItemSelected(item);
}
or set listener for toolbar when create it in onCreateView():
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
return false;
}
});