2012年2月9日星期四

使用 Java 程序碼實現動作欄(Action Bar)

前面一些文章示範如何通過 XML 文件定義動作欄(Action Bar). 這篇文章示範如何使用 Java 程序碼實現動作欄(Action Bar).

使用 Java 程序碼實現動作欄(Action Bar)

像下面修改 Activity 中的 onCreateOptionsMenu(Menu menu) 方法實現動作欄, 同時修改 onOptionsItemSelected(MenuItem item) 的 switch-case 處理對應的數值.
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) {
super.onCreateOptionsMenu(menu);

MenuItem menuItem0 = menu.add(0, 0, 0, "done");
//(groupId, itemId, order, title)
menuItem0.setIcon(R.drawable.ic_action_done);
menuItem0.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM
|MenuItem.SHOW_AS_ACTION_WITH_TEXT);

MenuItem menuItem1 = menu.add(0, 1, 1, "photo");
menuItem1.setIcon(R.drawable.ic_action_photo);
menuItem1.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM
|MenuItem.SHOW_AS_ACTION_WITH_TEXT);

MenuItem menuItem2 = menu.add(0, 2, 2, "refresh");
menuItem2.setIcon(R.drawable.ic_action_refresh);
menuItem2.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM
|MenuItem.SHOW_AS_ACTION_WITH_TEXT);

MenuItem menuItem3 = menu.add(0, 3, 3, "star");
menuItem3.setIcon(R.drawable.ic_action_star);
menuItem3.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM
|MenuItem.SHOW_AS_ACTION_WITH_TEXT);

MenuItem menuItem4 = menu.add(0, 4, 4, "user");
menuItem4.setIcon(R.drawable.ic_action_user);
menuItem4.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM
|MenuItem.SHOW_AS_ACTION_WITH_TEXT);

MenuItem menuItem5 = menu.add(0, 5, 5, "add user");
menuItem5.setIcon(R.drawable.ic_action_user_add);
menuItem5.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM
|MenuItem.SHOW_AS_ACTION_WITH_TEXT);

return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch(item.getItemId()){
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
Toast.makeText(Android3ActionBarActivity.this,
item.getTitle(),
Toast.LENGTH_LONG).show();
return true;
default:
return false;
}

}

}

沒有留言:

發佈留言