Search code examples
javaandroidxmlandroid-actionbarandroid-toolbar

Unable to show icon on toolbar


I tried all the solutions but still unable to show icon on toolbar, in my main project I have a toolbar and under it toolbar and inside toolbar, fragments, no matter what I tried I'm unable to show icon on toolbar, here is mainActivity.java which extends AppCompatActivity

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_act_main_screen);

    Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
    setSupportActionBar(myToolbar);

    ActionBar ab = getSupportActionBar();
    ab.setTitle("Title");


    tabs = (TabLayout) findViewById(R.id.tabs);
    tabs.addTab(tabs.newTab().setText("Today"),true);
    tabs.addTab(tabs.newTab().setText("Settings"));

    tabs.setOnTabSelectedListener(this);
}

     @Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

styles.xml

 <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
 </style>

menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"

tools:context="address">

<item
    android:id="@+id/action_settings"
    android:title="@string/action_settings"
    app:showAsAction="always"
    //android:showAsAction="always" tried this as well
    android:icon="@drawable/share"/>

mainactivity.xml

<android.support.v7.widget.Toolbar
    android:id="@+id/my_toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/toolbarColor"
    android:elevation="3dp">
</android.support.v7.widget.Toolbar>

<android.support.design.widget.TabLayout
    android:id="@+id/tabs"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabGravity="fill"
    app:tabMode="fixed"
     />

Nothing is working, not sure abou how to implement custom namespace but I changed name from app to custom but didn't work also there is enough space but still doesn't show.


Solution

  • I always do this for toolbar's title and icon :

    Because I don't have access to a computer right now , I cant post a complete sample but I'll describe :

    First set your toolbar height like this : layout_height="android:?attr/actionBarSize" then in the android.support.v7.widget.Toolbar tag put a LinearLayout with these attributes : android:layout_width="match_parent and android:layout_height="match_parent" and android:gravity="center_vertical|left" then put an ImageView in the LinearLayout with these attributes:

    width="wrap_content"
    height="match_parent"
    scaleType="fitXY"
    adjustviewbounds="true"
    src="@drawable/icon"
    

    if you want to add a title just add a text view after adding the ImageView.