Android Menu:使用Popup Menu


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

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

效果如下:

Android Menu:使用Popup Menu_第1张图片

代码如下:

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>



你可能感兴趣的:(android,用户体验,popup,menu)