将图标添加到工具栏 Android

Kes*_*lme 2 android android-actionbar android-toolbar

我正在尝试使用这两行将图标添加到我的工具栏

getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setIcon(R.drawable.logo);
Run Code Online (Sandbox Code Playgroud)

图标已添加,但它添加在工具栏的中心,例如,如何将其添加到工具栏的右上角?

这是我的 action_bar_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/app_name"
        android:textColor="#ffffff"
        android:id="@+id/action_bar_text"
        android:textSize="18sp" />

</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

lib*_*ib4 5

没有直接的方法可以在工具栏中将图标设置为向右。另一种方法是使用菜单。

您可以执行以下操作

在 res/menu.xml 文件夹中创建一个 Menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">

    <item android:id="@+id/menu_item"
          android:icon="@drawable/logo"
          app:showAsAction="always"/>

</menu>
Run Code Online (Sandbox Code Playgroud)

在 Activity 中实现以下方法。

@Override
public boolean onCreateOptionsMenu(Menu menu){
    getMenuInflater().inflate(R.menu.right_menu, menu);
    return super.onCreateOptionsMenu(menu);
}
Run Code Online (Sandbox Code Playgroud)

现在通过上述更改,您将在工具栏右侧看到图标。

您可以使用以下方法实现水龙头:-

    @Override
    public boolean onOptionsItemSelected(MenuItem item){

        switch(item.getItemId()){
            case R.id.menu_item:   //this item has your app icon
                Toast.makeText(this,"Tapped on icon",Toast.LENGTH_SHORT).show();
                return true;
            default: return super.onOptionsItemSelected(item);
        }
    }
Run Code Online (Sandbox Code Playgroud)