Can I add an image to the toolbar?

I need information about the Toolbar . I would like to add four images to my Toolbar at home, news, search and message. So I put Imageview in the Toolbar . Now I do not know how to add a listener to these images ... how can I do this? I also have a navigation box, and I want that if you click Imageview in the Toolbar , you will be transferred to a new Fragment , not a new Activity . So how could I do these two things? Thanks for answers.

+6
source share
3 answers

I think you know how to add an imageView to your ToolBar if you don't check this one . After that, get a link to your ToolBar using findViewById

 Toolbar tool = finViewById(R.id.mytoolbar);//cast it to ToolBar ImageView im1 = tool.findViewById(R.id.myimageviewone); // cast it //same for the others // now you can set your click listeners //in your onclick listeners you use fragmentmanager along with fragmenttransaction //to start a new fragment in your layout or on your layout, you can google // for that 
+6
source

I would recommend using ImageButton s. You can set the image sources to be displayed as Button , and they behave like a normal Button with OnClickListeners .

0
source

You should simply use the regular MenuItem functionality built into the Toolbar (and the same as the ActionBar). Browse through any ActionBar tutorial and learn about usage by creating MenuItems (you'll do most of this in XML). You can then use the OS infrastructure to capture onClickListenter s.

Here are the docs (you'll notice that MenuItem has an icon attribute that will put images in the Toolbar ):

Android: icon = "@ hood / ic_new_game"

Docs: http://developer.android.com/guide/topics/ui/menus.html

0
source

Source: https://habr.com/ru/post/987335/


All Articles