Toolbar修改MenuItem字体颜色及布局

一、style方式


<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/colorPrimary"
    android:minHeight="?attr/actionBarSize"
    app:colorControlNormal="@android:color/white"
    app:navigationIcon="@drawable/back"
    app:theme="@style/ToolBarStyle">

二、ActionProvider方式(方式1一般写完之后全局都变了,如果需要动态更换或者个别地方更改则可以使用该方式)

public class MainActionProvider extends ActionProvider {


    TextView tvTitle;

    View.OnClickListener clickListener;


    public MainActionProvider(Context context) {
        super(context);
    }

    @Override
    public View onCreateActionView() {
        Log.e("toolbar-menu", "onCreateActionView");
        tvTitle = new TextView(getContext());
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.MATCH_PARENT);
        tvTitle.setLayoutParams(params);
        tvTitle.setGravity(Gravity.CENTER);
        tvTitle.setPadding(DensityUtils.dp2px(getContext(),10),0,DensityUtils.dp2px(getContext(),10),0);
        tvTitle.setText(R.string.exit);
        tvTitle.setBackgroundResource(R.drawable.half_translucent_selector);
        tvTitle.setTextColor(BSSUtils.getColor(R.color.red_exit));
        tvTitle.setOnClickListener(clickListener);


        return tvTitle;//或者自己写的布局inflate为View
    }


    @Override
    public void onPrepareSubMenu(SubMenu subMenu) {

    }

    @Override
    public boolean hasSubMenu() {
        return true;
    }

    public void setonClickListener(View.OnClickListener listener){
        clickListener = listener;
    }

    public void setTvTitle(String title){
        tvTitle.setText(title);
    }

}

在Activity中添加如下代码

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        mLogoutMenuItem = menu.findItem(R.id.logout);
        mLogoutMenuItem.setVisible(false);
//        mLogoutMenuItem.getActionView();
        MainActionProvider actionProvider = (MainActionProvider) MenuItemCompat.getActionProvider(mLogoutMenuItem);
        actionProvider.setonClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //点击事件
            }
        });
        return true;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return super.onCreateOptionsMenu(menu);
    }

参考:http://blog.csdn.net/u011102153/article/details/53072105

你可能感兴趣的:(Android)