import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.TextView; public class MainActivity extends Activity { private TextView textView;
private float fontSize =15;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); textView = (TextView) findViewById(R.id.textView);
}
//弹出菜单是3.0开始出现的,所以api最低为11
public void btnClick(View v)
{
//第二个参数是弹出菜单显示的参考位置,通常在参考视图的下边显示
//创建一个弹出菜单对象
PopupMenu pop = new PopupMenu(this, v); //给菜单添加菜单项
getMenuInflater().inflate(R.menu.main, pop.getMenu()); //给菜单项添加事件监听
pop.setOnMenuItemClickListener(new OnMenuItemClickListener() { @Override
public boolean onMenuItemClick(MenuItem item) {
switch(item.getItemId())
{
case R.id.action_add:
fontSize+=5;
textView.setTextSize(fontSize);
break;
case R.id.action_sub:
fontSize-=5;
textView.setTextSize(fontSize);
break;
case R.id.action_background:
int red = (int)(Math.random()*256);
int green = (int)(Math.random()*256);
int blue = (int)(Math.random()*256);
textView.setBackgroundColor(Color.rgb(red, green, blue));
break;
}
return false;
}
}); //显示菜单
pop.show();
} }

MainActivity

 <menu xmlns:android="http://schemas.android.com/apk/res/android" >

      <item
android:id="@+id/action_add"
android:orderInCategory="100"
android:showAsAction="never"
android:title="放大字体"/>
<item
android:id="@+id/action_sub"
android:orderInCategory="100"
android:showAsAction="never"
android:title="缩小字体"/>
<item
android:id="@+id/action_background"
android:orderInCategory="100"
android:showAsAction="never"
android:title="改变背景颜色"/> </menu>

menu_main

05-11 19:35