In this posting, we can learn how to use the Action Bar, simply.
Action items appear directly in the action bar with an icon or text are known as action buttons.
Actions that can't fit in the action bar or aren't important enough are hidden in the action overflow.
Now, here's how to add the Action Bar.
1. Specify the Actions in XML
First, we should define in an XML menu resource for all action buttons and other items available in the action overflow.
we create a new XML file in our project's 'res/menu/' directory.
==== res/menu/main.xml ====
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/menu_refresh"
android:title="@string/menu_refresh"
android:icon="@drawable/menu_refresh"
android:orderInCategory="101"
android:showAsAction="always" />
<item android:id="@+id/menu_search"
android:title="@string/menu_search"
android:icon="@drawable/menu_search"
android:orderInCategory="102"
android:showAsAction="always|withText" />
<item android:id="@+id/menu_settings"
android:title="@string/menu_settings"
android:icon="@drawable/menu_settings"
android:orderInCategory="103"
android:showAsAction="never" />
</menu>
: Add an <item> element for each item you want to include in the action bar.
In icon case, we can use icons provided in "http://developer.android.com/design/downloads/index.html#action-bar-icon-pack"
2. Add the Actions to the Action Bar
@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;
}
: We should implement onCreateOptionsMenu() callback method in our activity to inflate the menu resource into the given Menu object.
3. Respond to Action Buttons
/**
* This method is called automatically, when ActionBar's menu is selected.
*
* @param item
* @return
*/
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch(item.getItemId()){
case R.id.menu_refresh:
text01.setText("새로고침 메뉴 선택!!");
return true;
case R.id.menu_search:
text01.setText("검색 메뉴 선택!!");
return true;
case R.id.menu_settings:
text01.setText("설정 메뉴 선택");
return true;
}
return super.onOptionsItemSelected(item);
}
: When the user presses one of the action buttons, the Android system calls our activity's onOptionsItemSelected() callback method.
We can call getItemId() method to determine which item was pressed. And then The returned ID can match the value we declared in the corresponding <item> element's android:id attributes.
The result let us run the application is the following.
'Android > Activity' 카테고리의 다른 글
Staring Another Activity (0) | 2014.02.03 |
---|