Menu练习

本文介绍了一个Android应用程序中菜单的设计和实现方法,包括选项菜单、上下文菜单和弹出菜单等不同类型的菜单,并演示了如何通过代码来响应菜单项的点击事件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

MainActivity.java

package com.example.bestone.test6;

import android.content.DialogInterface;
import android.graphics.Color;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.Button;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import java.lang.reflect.Field;

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;

    private TextView tv_test;
    private TextView tv_context;

    private Button btn_show_menu1;
    private Button btn_show_menu2;
    private Button btn_show_menu3;
    private Button btn_show_menu4;
    private AlertDialog alert = null;
    private AlertDialog.Builder builder = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        makeActionOverflowMenuShown();
        setContentView(R.layout.activity_main);

        tv_test = (TextView) findViewById(R.id.txt_topbar);
        tv_context = (TextView) findViewById(R.id.txt_topbar);      //为测试文字添加上下文菜单
       registerForContextMenu(tv_context);

        btn_show_menu1 = (Button)findViewById(R.id.fontsize);
        btn_show_menu1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PopupMenu popup = new PopupMenu(MainActivity.this,btn_show_menu1);
                popup.getMenuInflater().inflate(R.menu.menu_pop, popup.getMenu());
                popup.show();
            }
        });

        btn_show_menu2 = (Button)findViewById(R.id.fontcolor);
        btn_show_menu2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String[] lesson = new String[]{"红色", "绿色", "蓝色", "黄色"};
                alert = null;
                builder = new AlertDialog.Builder(MainActivity.this);
                alert = builder.setIcon(R.mipmap.tf1)
                        .setTitle("请选择字体颜色")
                        .setItems(lesson, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(getApplicationContext(), "你选择了" + lesson[which], Toast.LENGTH_SHORT).show();
                            }
                        }).create();
                alert.show();

            }
        });


        btn_show_menu3 = (Button)findViewById(R.id.exit);
        btn_show_menu3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                builder = new AlertDialog.Builder(MainActivity.this)         //创建
                        .setTitle("确定退出?") ;                            //对话框内容

                builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {     //按钮
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                });
                builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                }).create().show();
            }
        });


        btn_show_menu4 = (Button)findViewById(R.id.more);
        btn_show_menu4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PopupMenu popup = new PopupMenu(MainActivity.this,btn_show_menu4);
                popup.getMenuInflater().inflate(R.menu.menu_pop, popup.getMenu());
                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        switch (item.getItemId()){
                            case R.id.about:
                                Toast.makeText(MainActivity.this,"你点了关于",
                                        Toast.LENGTH_SHORT).show();
                                break;
                            case R.id.help:
                                Toast.makeText(MainActivity.this,"你点了帮助",
                                        Toast.LENGTH_SHORT).show();
                                break;
                        }
                        return true;
                    }
                });
                popup.show();
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {                //选项菜单
        // Inflate the menu; this adds items to the action bar if it is present.
        SubMenu subMenu1 = menu.addSubMenu(0, 1, Menu.NONE, "字体大小").setIcon(android.R.drawable.ic_menu_send);
            subMenu1.add(0,10,0,"10号字体");
            subMenu1.add(0,14,0,"14号字体");
            subMenu1.add(0,18,0,"18号字体");

        SubMenu subMenu = menu.addSubMenu(1,2,Menu.NONE, "字体颜色").setIcon(android.R.drawable.ic_menu_share);
            //添加子菜单项
            subMenu.add(1,YELLOW,1,"黄色");
            subMenu.add(1,GREEN,2,"绿色");
            subMenu.add(1,BLUE,3,"蓝色");
            subMenu.add(1,RED,4,"红色");
        menu.add(2,3,Menu.NONE,"更多");
        menu.add(2,4,Menu.NONE,"退出");
        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 10:
                tv_test.setTextSize(10*2);
                break;
            case 14:
                tv_test.setTextSize(14*2);
                break;
            case 18:
                tv_test.setTextSize(18*2);
                break;

            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;
        }
        return super.onOptionsItemSelected(item);
    }

    private void makeActionOverflowMenuShown() {      //此方法解决手机右上角不显示菜单按钮
        //devices with hardware menu button (e.g. Samsung Note) don't show action overflow menu
        try {
            ViewConfiguration config = ViewConfiguration.get(this);
            Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
            if (menuKeyField != null) {
                menuKeyField.setAccessible(true);
                menuKeyField.setBoolean(config, false);
            }
        } catch (Exception e) {

        }
    }



    //重写与ContextMenu相关方法
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {  //重写上下文菜单的创建方法
        MenuInflater inflator = new MenuInflater(this);
        inflator.inflate(R.menu.menu_context, menu);
        super.onCreateContextMenu(menu, v, menuInfo);
    }
    @Override
    public boolean onContextItemSelected(MenuItem item) {      //上下文菜单被点击是触发该方法
        switch (item.getItemId()) {
            case R.id.blue:
                tv_context.setTextColor(Color.BLUE);
                break;
            case R.id.green:
                tv_context.setTextColor(Color.GREEN);
                break;
            case R.id.red:
                tv_context.setTextColor(Color.RED);
                break;
        }
        return true;
    }


}


activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <RelativeLayout
        android:id="@+id/ly_top_bar"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:background="@color/bg_topbar">

        <TextView
            android:id="@+id/txt_topbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_centerInParent="true"
            android:gravity="center"
            android:textSize="18sp"
            android:textColor="@color/text_topbar"
            android:text="这是测试文字"/>
        <View
            android:layout_width="match_parent"
            android:layout_height="2px"
            android:background="@color/div_white"
            android:layout_alignParentBottom="true"/>
    </RelativeLayout>


    <LinearLayout
        android:id="@+id/ly_tab_bar"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:layout_alignParentBottom="true"
        android:background="@color/bg_white"
        android:orientation="horizontal">

        <Button
            android:id="@+id/fontsize"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/tab_menu_bg"
            android:drawablePadding="3dp"
            android:drawableTop="@drawable/more"
            android:gravity="center"
            android:padding="5dp"
            android:text="字体大小"
            android:textColor="@drawable/tab_menu_text"
            android:textSize="16sp" />
        <Button
            android:id="@+id/fontcolor"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/tab_menu_bg"
            android:drawablePadding="3dp"
            android:drawableTop="@drawable/more"
            android:gravity="center"
            android:padding="5dp"
            android:text="字体颜色"
            android:textColor="@drawable/tab_menu_text"
            android:textSize="16sp" />
        <Button
            android:id="@+id/exit"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/tab_menu_bg"
            android:drawablePadding="3dp"
            android:drawableTop="@drawable/more"
            android:gravity="center"
            android:padding="5dp"
            android:text="退出"
            android:textColor="@drawable/tab_menu_text"
            android:textSize="16sp" />
        <Button
            android:id="@+id/more"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/tab_menu_bg"
            android:drawablePadding="3dp"
            android:drawableTop="@drawable/more"
            android:gravity="center"
            android:padding="5dp"
            android:text="更多"
            android:textColor="@drawable/tab_menu_text"
            android:textSize="16sp" />
    </LinearLayout>

    <View
        android:id="@+id/div_tab_bar"
        android:layout_width="match_parent"
        android:layout_height="2px"
        android:background="@color/div_white"
        android:layout_above="@id/ly_tab_bar"/>


    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/ly_content"
        android:layout_below="@+id/ly_top_bar"
        android:layout_above="@+id/ly_tab_bar">
    </FrameLayout>

</RelativeLayout>


效果图:



长按测试文字



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值