Adding toolbar to a FragmentActivity

核能气质少年 提交于 2020-01-23 08:09:31

问题


Am extending a FragmentActivity in a class which serves as my base activity where my other activities extend from. My issue is when I extend my other activities from my base activity, I loose toolbar functionality. How can I add this to my base activity so that my activities can inherit the toolbar? Any pointers?


回答1:


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
        ActionBarActivity activity = (ActionBarActivity) getActivity();
        activity.setSupportActionBar(toolbar);
        activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

menu listener could be created two ways:

1.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);
}

2.set listener for toolbar when create it in onCreateView():

toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                return false;
            }
});



回答2:


You should extend your Activity from AppCompatActivity as this includes support for Fragments and the Toolbar

public class MainActivity extends AppCompatActivity { ...

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    FragmentTransaction ft = getSupportFragmentManager.beginTransaction();
    ....
    ....


来源:https://stackoverflow.com/questions/30148276/adding-toolbar-to-a-fragmentactivity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!