自定义 ActionBar

1 . 创建布局 actionbar_custom.xml




    

2 . activity 中设置 actionbar

ActionBar actionBar =  getSupportActionBar();
        View actionbarView = LayoutInflater.from(this).inflate(R.layout.actionbar_custom,null);
        ActionBar.LayoutParams layoutParams = new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT,
                ActionBar.LayoutParams.MATCH_PARENT);
        layoutParams.gravity = Gravity.CENTER_HORIZONTAL |Gravity.CENTER_HORIZONTAL;
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        actionBar.setDisplayShowCustomEnabled(true);
        actionBar.setDisplayShowHomeEnabled(true);
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setCustomView(actionbarView, layoutParams);
        Toolbar parent =(Toolbar) actionbarView.getParent();
        parent.setContentInsetsAbsolute(0,0);

3 . actionbar显示返回按钮

getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);

public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            this.finish(); // back button
            return true;
    }
    return super.onOptionsItemSelected(item);
}

你可能感兴趣的:(自定义 ActionBar)