Wednesday, March 26, 2014

Use action bar on API8(below Android 3.0).

1. What is action bar?
You can find informatio about android action bar in below site.

http://developer.android.com/guide/topics/ui/actionbar.html

2. How to use action bar in API8?
You can find the info from above site...

The ActionBar APIs were first added in Android 3.0 (API level 11) but they are also available in the Support Library for compatibility with Android 2.1 (API level 7) and above.

  • What is support library?
http://developer.android.com/tools/support-library/index.html

  • How to setup support library?
http://developer.android.com/tools/support-library/setup.html

  • It seems that the support 7 library is already included if you create project with selecting API8 of the option 'Minimum Required SDK' and action bar can be used in the latest version of EClipse.
3. Add menu to res>>menu folder of the project.

[example] res>>menu>>main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.helloworld.MainActivity" >
<item
android:id="@+id/action_exit"
android:orderInCategory="101"
app:showAsAction="ifRoom"
android:title="exit"
android:icon="@drawable/btn_exit"/>
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:title="@string/action_settings"
android:icon="@drawable/btn_exit"
app:showAsAction="ifRoom"/>
</menu>

 

4. The codes in the activity.
  • When creating activity, android.support.v7.app.ActionBarActivity should be extended.
example]
import android.support.v7.app.ActionBarActivity;
public class MainActivity extends ActionBarActivity {
  • Load option menu from main.xml.
@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;

}

 
  • Hanle action bar items.

@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_exit) {
     Toast.makeText(this, "Selected!" + item.getTitle(), Toast.LENGTH_LONG).show();
     return true;
}else if (id == R.id.action_settings) {
     Toast.makeText(this, "Selected!" + item.getTitle(), Toast.LENGTH_LONG).show();
     return true;
}
 
return super.onOptionsItemSelected(item);
}


No comments:

Post a Comment