Hornsey的博客

C/C++/Android/音视频加解密

Android Menu:使用Popup Menu


Popup Menu和Context menu有些类似,都是指定某个view弹出菜单,但Context Menu需要长按,用户体验较差。Popup Menu使用自定义方式启动,比如单击启动,用户体验会更换。

实现原理很简单,在某个view上添加单击监听事件,触发显示Popup Menu菜单,然后监听菜单的点击事件,做出处理。

效果如下:


代码如下:

public class PopupMenuActivity extends Activity {
    private static final String TAG = "PopupMenuActivity";
    private Context context;

    private View view;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_popup_menu);

        context = PopupMenuActivity.this;

        view = (View) findViewById(R.id.view);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopupMenu(v);
            }
        });
    }

    private void showPopupMenu(View view) {

        PopupMenu popup = new PopupMenu(context, view, Gravity.CENTER_HORIZONTAL);

        popup.getMenuInflater().inflate(R.menu.menu_popup_menu, popup.getMenu());

        popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                switch (menuItem.getItemId()) {
                    case R.id.action_settings:
                        Log.d(TAG, "onMenuItemClick action_settings");
                        return true;
                    case R.id.action_test:
                        Log.d(TAG, "onMenuItemClick action_test");
                        return true;
                }
                return false;
            }
        });

        popup.show();
    }


}

这里使用的是xml定义的菜单,也很简单:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.hornsey.myapplication.Demo.PopupMenuActivity">
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="@string/action_settings"
        app:showAsAction="never" />
    <item
        android:id="@+id/action_test"
        android:orderInCategory="101"
        android:title="@string/hello_world"
        app:showAsAction="never" />

</menu>



阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/nalw2012/article/details/49909525
个人分类: Android
上一篇android studio 使用gradle 导出jar包,并打包assets目录
下一篇按字母排列的中国城市名称大全
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭