Android ActionBar选项长按事件

use*_*890 4 android click long-click android-actionbar

Android任何人都可以知道有关Actionbar项目选项的长按,我想在LongClick的动作栏菜单选项上显示文本,就像长按动作提示一样长按

Yee*_*hin 10

你想长时间按动作栏上的菜单项吗?至于我,在找到2,3小时后,我找到了这个解决方案.这对我来说非常合适.

      @Override
     public boolean onCreateOptionsMenu(final Menu menu) {



    getMenuInflater().inflate(R.menu.menu, menu);

    new Handler().post(new Runnable() {
        @Override
        public void run() {
            final View v = findViewById(R.id.action_settings);

            if (v != null) {
                v.setOnLongClickListener(new CustomLongOnClickListener());
            }
        }
    });

    return true;
}
Run Code Online (Sandbox Code Playgroud)


Yur*_*rev 5

user1206890,您不需要听长按事件.如果要显示动作提示,将在菜单添加中设置足够的标题.检查2.3和4.0.


Jör*_*eld 5

对我来说,以下方法适用于较新的Android版本 - 我使用Android 4.2和Android 5.0.1进行了测试.

我的想法是我用自定义视图替换动作图标视图.在这里,我必须处理单击,我可以处理长按.

如果我希望外观与正常的操作栏图标完全相同,则以下工作方式.

首先,使用您的图标创建一个仅包含ImageButton的布局.

<?xml version="1.0" encoding="utf-8"?>
<ImageButton xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/myButton"
    style="?android:attr/actionButtonStyle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:contentDescription="@layout/text_view_initializing"
    android:src="@drawable/ic_action_plus" />
Run Code Online (Sandbox Code Playgroud)

然后将此ImageButton放入操作栏并将侦听器附加到它.

MenuItem myItem = menu.findItem(R.id.my_action);
myItem.setActionView(R.layout.my_image_button);
myItem.getActionView().setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(final View v) {
        // here, I have to put the stuff that normally goes in onOptionItemSelected 
    }
});
myItem.getActionView().setOnLongClickListener(new OnLongClickListener() {
    @Override
    public boolean onLongClick(final View v) {
        // here, I put the long click stuff
    }
});
Run Code Online (Sandbox Code Playgroud)

重要说明:仅当项目出现在操作栏中时才会起作用.因此,如果选项出现在菜单下拉列表中,则无法以这种方式访问​​长按所需的任何操作.