Add Icon to the left of the title in the action bar in android

后端 未结 7 1780
旧时难觅i
旧时难觅i 2021-02-07 01:07

I want to add a clickable icon/button to the left of the title in the action bar . How to do it? Following is the code with which I have added search and setting icon to the act

7条回答
  •  青春惊慌失措
    2021-02-07 01:38

    You can replace default navigation icon (and button of cause) in following way.

    Define usual UI with toolbar in your XML:

    
    
    
        
    
            
    
        
    
        
    
    
    

    Then setup your Toolbar as ActionBar in onCreate method

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu);
    
        Toolbar toolbar = findViewById(R.id.toolbar);
    
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true); // Make toolbar show navigation button (i.e back button with arrow icon)
    
        toolbar.setNavigationIcon(R.drawable.custom_icon); // Replace arrow icon with our custom icon
    }
    

    Handle back navigation button in onOptionsItemSelected method:

    @Override
        public boolean onOptionsItemSelected(MenuItem menuItem) {
            if (menuItem.getItemId() == android.R.id.home) {
    
                // Do whatever you want
    
                return true;
            }
    
            return super.onOptionsItemSelected(menuItem);
        }
    

    The same in Kotlin

    class MainActivity : AppCompatActivity() {
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
            setSupportActionBar(toolbar)
    
            supportActionBar?.setDisplayHomeAsUpEnabled(true) // Important step, we enable button on the left side of the toolbar
    
            toolbar.navigationIcon = getDrawable(R.drawable.custom_icon) // Here we change default navigation button icon
    
        }
    
        override fun onOptionsItemSelected(item: MenuItem): Boolean {
            return when (item.itemId) {
                android.R.id.home -> {
                    doSomething() // Here we can perform any action
                    true
                }
                else -> super.onOptionsItemSelected(item)
            }
        }
    
        private fun doSomething() {
            Toast.makeText(this, "Hello", Toast.LENGTH_LONG).show()
        }
    }
    

    Result:

提交回复
热议问题