Actionbar is widely used and can be used as a tool bar. This topic describes how to use actionbar.
1. actionbar generally contains multiple tool buttons. Therefore, you need to create an XML file to store the content in the actionbar. Create a menu folder under the res folder of the program, and create an XML file named optionmenu in the menu.
Note: You need to create it under the menu element. In this way, you can directly generate the menu code in XML.
2. Add the actionbar content layout to optionmenu. xml. Because the item in the actionbar of this article uses the image background, create a new drawable folder under Res to store the background image, the picture can be downloaded in the following website http://www.easyicon.net/(personal think, this URL is very convenient)
<?xml version="1.0" encoding="utf-8"?><menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/zoomin" android:icon="@drawable/zoomin" android:title="放大" android:showAsAction="always"/> <item android:id="@+id/zoomout" android:icon="@drawable/zoomout" android:title="缩小" android:showAsAction="always"/> <item android:id="@+id/mapscreen" android:icon="@drawable/map" android:title="全图" android:showAsAction="always"/> <item android:id="@+id/clear" android:icon="@drawable/clear" android:title="清除" android:showAsAction="always"/> </menu>
3. After the layout is complete, set the display of the actionbar in the activity. Add code to the oncreate function:
ActionBar actionBar = this.getActionBar();actionBar.setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP, ActionBar.DISPLAY_HOME_AS_UP);
4. This defines the actionbar. In the next step, you need to find the newly defined XML file. This requires rewriting of the onoptionsitemselected function.
@Overridepublic boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.optionmenu, menu); //SearchView searchView = (SearchView) menu.findItem(R.id.actionview).getActionView(); return true; }
5. At this step, we can see:
6. Click events
1 @Override 2 public boolean onOptionsItemSelected(MenuItem item){ 3 switch (item.getItemId()) { 4 case android.R.id.home: 5 Toast.makeText(this, "单击了图标", Toast.LENGTH_SHORT).show(); 6 return true; 7 case R.id.zoomin: 8 Toast.makeText(this, "放大", Toast.LENGTH_SHORT).show(); 9 return true;10 case R.id.zoomout:11 Toast.makeText(this, "缩小", Toast.LENGTH_SHORT).show();12 return true;13 case R.id.mapscreen:14 Toast.makeText(this, "全图", Toast.LENGTH_SHORT).show();15 return true;16 case R.id.clear:17 Toast.makeText(this, "清除", Toast.LENGTH_SHORT).show();18 return true;25 default:26 return super.onOptionsItemSelected(item);27 }28 }
In addition, you can change the project title image: In androidmanifest. XML, modify the value of Android: icon in the <Application> tag to OK.
Use of actionbar