Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add icons in actionbar when its setSupportActionBar

Tags:

android

I have the below code that set the toolbar

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
   list = (ListView) findViewById(R.id.ListView);
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
    //downloadImage();
}

should I add this code ?

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);

What I want to have icons in the toolbar action bar how to do that ?

like image 379
Moudiz Avatar asked Dec 09 '22 01:12

Moudiz


1 Answers

Yes you should add

   @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
 //and this to handle actions
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

to add icons ,go to main.xml under menu directory and add

<item android:id="@+id/action_settings" 
        android:title="@string/action_settings"
        android:icon="@drawable/icon"
        android:orderInCategory="100" 
        app:showAsAction="always" />
like image 54
Mrad Mrad Avatar answered Dec 11 '22 10:12

Mrad Mrad