定制动作项和应用程序图标

作者:追风剑情 发布于:2015-7-26 11:37 分类:Android

package com.example.androidtest;

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

public class MyActionBarActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_my_action_bar);
		
		ActionBar actionBar = getActionBar();
		//使应用程序图标可点击
		actionBar.setDisplayHomeAsUpEnabled(true);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		CreateMenu(menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item){
		return MenuChoice(item);
	}
	
	private void CreateMenu(Menu menu){
		MenuItem menu1 = menu.add(0, 0, 0, "Item 1");
		{
			menu1.setIcon(R.drawable.ic_launcher);
			//SHOW_AS_ACTION_IF_ROOM: 如果Action Bar上有空间,则将该菜单项显示为一个动作项显示。
			//SHOW_AS_ACTION_WITH_TEXT: 显示文本。
			menu1.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
		}
		MenuItem menu2 = menu.add(0, 1, 1, "Item 2");
		{
			menu2.setIcon(R.drawable.ic_launcher);
			menu2.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
		}
		MenuItem menu3 = menu.add(0, 2, 2, "Item 3");
		{
			menu3.setIcon(R.drawable.ic_launcher);
			menu3.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
		}
		MenuItem menu4 = menu.add(0, 3, 3, "Item 4");
		{
			menu4.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
		}
		MenuItem menu5 = menu.add(0, 4, 4, "Item 5");
		{
			menu5.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
		}
	}
	
	private boolean MenuChoice(MenuItem item){
		switch(item.getItemId()){
		case android.R.id.home:
			Toast.makeText(this, "You clicked on the Application icon", Toast.LENGTH_LONG).show();
			Intent i = new Intent(this, MyActionBarActivity.class);
			//FLAG_ACTIVITY_CLEAR_TOP: back stack中的一系列活动被清除。这样,如果用户
			//单击Back按钮,应用程序中的其他活动就不会再次显示。
			i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(i);
			return true;
		case 0:
			Toast.makeText(this, "You clicked on Item 1", Toast.LENGTH_LONG).show();
			return true;
		case 1:
			Toast.makeText(this, "You clicked on Item 2", Toast.LENGTH_LONG).show();
			return true;
		case 2:
			Toast.makeText(this, "You clicked on Item 3", Toast.LENGTH_LONG).show();
			return true;
		case 3:
			Toast.makeText(this, "You clicked on Item 4", Toast.LENGTH_LONG).show();
			return true;
		case 4:
			Toast.makeText(this, "You clicked on Item 5", Toast.LENGTH_LONG).show();
			return true;
		}
		return false;
	}
}

运行效果

yyyyyyyy.png

标签: Android

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号