2012年2月3日星期五

處理動作欄(Action Bar)的用戶選項操作, onOptionsItemSelected()

重寫onOptionsItemSelected(MenuItem item)方法, 我們可以處理用戶的動作欄(Action Bar)選項.

處理動作欄(Action Bar)的用戶選項操作

package com.Android3ActionBar;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class Android3ActionBarActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

getMenuInflater().inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch(item.getItemId()){
case R.id.itemid_0:
case R.id.itemid_1:
case R.id.itemid_2:
case R.id.itemid_3:
case R.id.itemid_4:
case R.id.itemid_5:
Toast.makeText(Android3ActionBarActivity.this,
item.getTitle(),
Toast.LENGTH_LONG).show();
return true;
default:
return false;
}

}
}


<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/itemid_0"
android:title="Done"
android:orderInCategory="0"
android:icon="@drawable/ic_action_done"
android:showAsAction="ifRoom|withText" />
<item android:id="@+id/itemid_1"
android:title="Photo"
android:orderInCategory="0"
android:icon="@drawable/ic_action_photo"
android:showAsAction="ifRoom|withText" />
<item android:id="@+id/itemid_2"
android:title="Refresh"
android:orderInCategory="0"
android:icon="@drawable/ic_action_refresh"
android:showAsAction="ifRoom|withText" />
<item android:id="@+id/itemid_3"
android:title="Star"
android:orderInCategory="0"
android:icon="@drawable/ic_action_star"
android:showAsAction="ifRoom|withText" />
<item android:id="@+id/itemid_4"
android:title="User"
android:orderInCategory="0"
android:icon="@drawable/ic_action_user"
android:showAsAction="ifRoom|withText" />
<item android:id="@+id/itemid_5"
android:title="Add User"
android:orderInCategory="0"
android:icon="@drawable/ic_action_user_add"
android:showAsAction="ifRoom|withText" />
</menu>

沒有留言:

發佈留言