1.选项菜单(选项菜单)
1)如何使用选项菜单?
答:非常简单,重写两个方法就好,其实这两个方法我们在创建项目的时候就会自动生成~ 他们分别是:
- public boolean onCreateOptionsMenu(Menu menu):调用OptionMenu,在这里完成菜单初始化
- public boolean onOptionsItemSelected(MenuItem item):菜单项被选中时触发,这里完成事件处理
当然除了上面这两个方法我们可以重写外我们还可以重写这三个方法:
- public void onOptionsMenuClosed(Menu menu):菜单关闭会调用该方法
- public boolean onPrepareOptionsMenu(Menu menu):选项菜单显示前会调用该方法, 可在这里进行菜单的调整(动态加载菜单列表)
- public boolean onMenuOpened(int featureId, Menu menu):选项菜单打开以后会调用这个方法
而加载菜单的方式有两种,一种是直接通过编写菜单XML文件,然后调用: getMenuInflater().inflate(R.menu.menu_main, menu);加载菜单 或者通过代码动态添加,onCreateOptionsMenu的参数menu,调用add方法添加 菜单,add(菜单项的组号,ID,排序号,标题),另外如果排序号是按添加顺序排序的话都填0即可!
代码实现:
主要活动.java:
public class MainActivity extends AppCompatActivity { //1.定义不同颜色的菜单项的标识: final private int RED = 110; final private int GREEN = 111; final private int BLUE = 112; final private int YELLOW = 113; final private int GRAY= 114; final private int CYAN= 115; final private int BLACK= 116; private TextView tv_test; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv_test = (TextView) findViewById(R.id.tv_test); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. menu.add(1,RED,4,"红色"); menu.add(1,GREEN,2,"绿色"); menu.add(1,BLUE,3,"蓝色"); menu.add(1,YELLOW,1,"黄色"); menu.add(1,GRAY,5,"灰色"); menu.add(1,CYAN,6,"蓝绿色"); menu.add(1,BLACK,7,"黑色"); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); switch (id){ case RED: tv_test.setTextColor(Color.RED); break; case GREEN: tv_test.setTextColor(Color.GREEN); break; case BLUE: tv_test.setTextColor(Color.BLUE); break; case YELLOW: tv_test.setTextColor(Color.YELLOW); break; case GRAY: tv_test.setTextColor(Color.GRAY); break; case CYAN: tv_test.setTextColor(Color.CYAN); break; case BLACK: tv_test.setTextColor(Color.BLACK); break; } return super.onOptionsItemSelected(item); } }
标签:总结,菜单,tv,menu,int,add,3.2,test,今日 From: https://www.cnblogs.com/psh888/p/17173366.html