更改左侧工具栏默认图标

Change ToolBar default icon on the left

我目前在顶部使用工具栏,想用主页按钮替换默认的后退按钮。但是当我添加项目时,它总是添加到右边。我也没有看到任何 layout_gravity 选项可供选择。有没有办法做到这一点?

主要活动

Toolbar toolbar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_delete);

    toolbar = (Toolbar)findViewById(R.id.app_bar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setTitle("                Testing");
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.home_icon_empty, menu);
    return true;
}

home_icon_empty.xml

<item
    android:id="@+id/homepage"
    android:orderInCategory="100"
    android:title="HOME"
    android:icon="@drawable/home_icon"
    app:showAsAction="always"
    />

<item
    android:id="@+id/homepage1"
    android:orderInCategory="200"
    android:title="HOME"
    android:icon="@drawable/home_icon"
    app:showAsAction="always"
    />

activity_main.xml

<include
        android:id="@+id/app_bar"
        layout="@layout/app_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

app_bar.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/colorPrimary">

</android.support.v7.widget.Toolbar>

当前工具栏输出:

预期的工具栏输出:

新编辑后的图片:

试试这个

toolbar.setNavigationIcon(R.drawable.your_icon);

在设置支持操作栏之前使用它。 不要称这个

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

或者至少

getSupportActionBar().setDisplayHomeAsUpEnabled(false);

试试吧。其中一些会起作用。

设置为导航图标:

Drawable drawable = ContextCompat.getDrawable(context, R.drawable.your_drawable)
toolbar.setNavigationIcon(drawable);
setSupportActionBar(toolbar);

根据 Material design guide 添加可绘制资源并在 Activity onCreate

中调用以下方法
private void setUpToolBar() {
            setSupportActionBar(toolbar);
            //Set Home screen icon
            getSupportActionBar().setHomeAsUpIndicator(R.drawable.home_screen_icon);

            //Enable Home icon
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);

            //Toolbar title
            getSupportActionBar().setTitle(getString(R.string.app_name));

           //Set toolbar as action bar
            setSupportActionBar(toolbar);
        }

您还可以:

mToolbar.setLogo( yourLogoID );

或者您可以:

mToolbar.setBackground( ContextCompat.getDrawable( yourContext, urBackgroundID );

哪里

mToolbar = yourToolbar;
mToolbar = findViewById(R.id.your_toolbar);
// or, if your toolbar get setted by a superclass
mToolbar = (Toolbar) getSupportActionBar();

您的风格应该是:Blablabla.NoActionBar 然后在 xml 布局中包含您的工具栏

如果您使用抽屉在向左滑动或单击主页按钮时显示左侧菜单,那么您应该使用上述方法之一(如果您不想超类化所有 DrawerLayout lul)

bb