下面用一个菜单来控制按钮的背景颜色:
package com.android.study;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.graphics.Color;
import android.view.View;
import android.view.Menu;
import android.view.Gravity;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnClickListener;
public class MainActivity extends Activity
{
private Button btn;
//对Menu的每一项进行定义
public static final int RED_MENU_ID = Menu.FIRST;
public static final int GREEN_MENU_ID = Menu.FIRST + 1;
public static final int BLUE_MENU_ID = Menu.FIRST + 2;
public void onCreate ( Bundle b )
{
super.onCreate ( b );
setContentView ( R.layout.main );
btn = ( Button ) findViewById ( R.id.btn );
}
public boolean onCreateOptionsMenu ( Menu menu )
{
super.onCreateOptionsMenu ( menu );
//第一个和第二个参数是整数值,代表组id和选项id,
//第三个参数代表是这个组别的第几个
//最后一个参数是item的名称
menu.add ( 0 , RED_MENU_ID , 0 , R.string.red );
menu.add ( 0 , GREEN_MENU_ID , 0 , R.string.green );
menu.add ( 0 , BLUE_MENU_ID , 0 , R.string.blue );
return true;
}
public boolean onOptionsItemSelected ( MenuItem item )
{
//对菜单项被点击后的处理
switch ( item.getItemId () )
{
case RED_MENU_ID:
btn.setBackgroundColor ( Color.RED );
btn.setText ( R.string.red );
return true;
case GREEN_MENU_ID:
btn.setBackgroundColor ( Color.GREEN );
btn.setText ( R.string.green );
return true;
case BLUE_MENU_ID:
btn.setBackgroundColor ( Color.BLUE );
btn.setText ( R.string.blue );
return true;
}
return super.onOptionsItemSelected ( item );
}
}