自定义操作栏菜单项在一次点击时没有响应

4
我已经为菜单项创建了自定义布局。现在,当单击时,我需要它加载一个新的活动。代码逻辑如下:
资源中的菜单声明:
<item android:id="@+id/shoppingCart"
    android:title="cart"
    android:background="@layout/basket_notification_counter"
    android:icon="@drawable/ic_add_shopping_cart_white_24dp"
    app:showAsAction="always" />

这个活动由各自选项卡下的碎片组成。根据我在SO上收集到的信息,我需要在片段的onCreateView方法中调用setHasOptionsMenu(true);,我已经这样做了。
现在,在活动中,两个主要的重要方法分别是onCreateOptionsMenuonOptionsItemSelected,如下所示:
package project.activities;

//... Imports come here


public class SalesActivity extends ActionBarActivity
{
    private final static String TAG = "PROJECT";

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

        // Setup the action bar
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showActionBar();
            }
        });
    }

    /**
     * Creates menus found the action bar
     *
     * @param menu the menu to work on
     * @return true
     */

    @Override
    public boolean onCreateOptionsMenu(final Menu menu)
    {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_sale, menu);

        final MenuItem item = menu.findItem(R.id.shopping_cart);
        // THIS IS THE PROBLEM
        // This workd but erratcally. After a number of clicks, it loads the activity specified in onOptionsItemSelected
        // This is random: sometimes one click, sometimes 2 or up to 7 clicks so far.
        item.getActionView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                menu.performIdentifierAction(item.getItemId(), 0);
            }
        });

        /**
         // Also tried this but didn't work. Didn't also throw an exception to tell something was wrong
        item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                LoggedInActivity.this.showCart();
                return true;
            }
        });
        */

        return true;
    }

    /**
     * Handles menus in lists
     *
     * @param item  the selected item
     * @return the selected item
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        int id = item.getItemId();
        switch (id) {
            case R.id.shopping_cart:
                Intent intent = new Intent(LoggedInActivity.this, CheckOutActivity.class);
                startActivity(intent);
                return true;
            case R.id.action_settings:
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    /**
     * When the screen is rotated, this method is called
     *
     * @param newConfig the new app configuration
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig)
    {
        super.onConfigurationChanged(newConfig);
    }

    /**
     * Recreates an item in cases where the app is pushed to the background
     *
     * @param savedInstanceState the bundle
     */
    @Override
    protected void onPostCreate(Bundle savedInstanceState)
    {
        super.onPostCreate(savedInstanceState);
    }

    /**
     * Handles the action bar
     */
    public void showActionBar()
    {
        // Initialize the action bar
        ActionBar actionBar = getSupportActionBar();
        //actionBar.setElevation(0);

        // Set up tabs
        showActionBarTabs(actionBar);
    }

    /**
     * Setup the actionbar tabs
     * @param actionBar the actionBar we get from the activity and style
     */
    public void showActionBarTabs(final ActionBar actionBar)
    {
        //... I set up the actionbar tabs here
    }
}

问题如下:在操作栏中点击菜单项时,它的工作方式相当“随机”。有时候,在点击一次后它会工作,而其他时候,需要点击4次或3次才能加载活动。没有一次点击的一致性。似乎存在什么问题?

尝试移除 android:clickable="false" - karan
8个回答

2
请在您的设备上尝试以下操作:

将此复制到您的

onCreateOptionsMenu(menu: Menu, inflater: MenuInflater)

method

Kotlin

inflater.inflate(R.menu.my_menu, menu)
menu.findItem(R.id.my_custom_item).actionView.setOnClickListener {
            println("КЛИК")
        }

最初的回答
Java
inflater.inflate(R.menu.my_menu, menu)
findItem(R.id.my_custom_item).getActionView().setOnClickListener(v -> System.out.println("click");

It worked for me


1

查看您的菜单项,可点击应为true或删除 android:clickable="fales" 和删除 android:actionLayout="@layout/basket_notification_counter",您的菜单项将如下所示。

<item android:id="@+id/shopping_cart"
    android:title="cart"
    android:icon="@drawable/ic_add_shopping_cart_white_24dp"
    android:clickable="true"
    app:showAsAction="always" />

或者

   <item android:id="@+id/shopping_cart"
        android:title="cart"
        android:icon="@drawable/ic_add_shopping_cart_white_24dp"
        app:showAsAction="always" />

没起作用。我之前把 clickable 改成了 false,想看看是否有帮助,但是没有。 - Armando Sudi
你是在尝试通过移除 android:clickable="false" 来实现吗? - Pacific P. Regmi
尝试了你提供的两个建议。我将 clickable 设置为 true,但没有任何变化。然后完全删除了该属性,但问题仍未解决。 - Armando Sudi
actionLayout="@layout/basket_notification_counter"更改为background="@layout/basket_notification_counter",但没有效果。 - Armando Sudi
我认为 actionLayout="@layout/basket_notification_counter" 不起作用。现在请删除 actionLayout="@layout/basket_notification_counter" 并运行您的应用程序。 - Pacific P. Regmi
确实如此,但没有任何效果。问题已更新为新的布局。 - Armando Sudi

0
问题出在您的自定义菜单项布局上。尝试为您的菜单添加自定义点击监听器。
<item android:id="@+id/shoppingCart"
android:title="cart"
android:background="@layout/basket_notification_counter"
android:icon="@drawable/ic_add_shopping_cart_white_24dp"
app:showAsAction="always" 
android:onClick="shoppingCartClickListener"/>

public void shoppingCartClickListener(View v) {
    // Process click here
}

希望这有所帮助。

0

不要使用android:actionLayout

使用此方法更改活动中的图标

public static Drawable convertLayoutToImage(Context mContext, int count, int drawableId) {
    LayoutInflater inflater = LayoutInflater.from(mContext);
    View view = inflater.inflate(R.layout.{your_custom_layout}, null);

    /*Edit other elements here*/

    view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
            View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
    view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());

    view.setDrawingCacheEnabled(true);
    view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
    Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
    view.setDrawingCacheEnabled(false);

    return new BitmapDrawable(mContext.getResources(), bitmap);
}

您必须编辑它以适应您的配置

要更改图标,请执行以下操作

menuItem.setIcon(Converter.convertLayoutToImage(localContext, 2, R.drawable.{your_drawable_resource}));

0

对于以上解决方案无法工作的人,

请确保您的<Toolbar><AppbarLayout>的子元素,类似于这样:

<com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent">

    <androidx.appcompat.widget.Toolbar
            android:background="@drawable/white_grey_border_bottom"
            android:id="@+id/homeActivityToolbar"
            android:layout_width="match_parent"
            app:titleTextColor="@color/dark_grey"
            android:layout_height="50dp" app:layout_constraintTop_toTopOf="parent"/>

</com.google.android.material.appbar.AppBarLayout>

顺便提一下,我的项目正在使用AndroidX,所以如果你要复制粘贴这段代码,请小心。


这对我的情况没有帮助 :/ - Alessandro Mautone
@AlessandroMautone 点击时没有任何反应? - devDeejay
1
它可以与AppBarLayout一起工作,也可以不使用它,只需确保按照先前的答案中所述操作:getActionView().setOnClickListener( // 在此处键入单击事件代码 } - Alessandro Mautone

0
遇到了类似的问题。已创建操作栏,但无法响应项目点击,特别是那些设置为showAsAction="always"的项目。
最终发现问题是由于我在onCreateOptionsMenu(...)方法内调用了invalidateOptionsMenu();引起的。
我进行了更改,问题得到了解决。

0

我曾经遇到过与我的应用程序相同的问题。操作栏已被创建,但无法响应点击。我之前在该活动中使用了相对布局,我将其更改为线性布局,并调整了小部件的大小和方向以使其看起来与以前相同。这对我解决了问题。你也可以试试。希望能帮到你 :)


0

由于您的活动布局根GroupView可能会阻止单击事件被分派到工具栏菜单项(如果您正在使用Toolbar并与CoordinatorLayout一起使用),因此您应该尝试添加

android:focusable="false"
android:clickable="false"

回到你的根GroupView

你还需要按照以下方式重写onOptionsItemSelected(Kotlin版本):

override fun onOptionsItemSelected(item: MenuItem): Boolean {
        super.onOptionsItemSelected(item)
        when (item.itemId) {
            R.id.menu_favorite -> {
                handleFavorite(item)
            }
        }
        return true
    }

不要忘记将 MenuItem 作为参数传递给您的函数,即使您没有使用它:

private fun handleFavorite(item: MenuItem) {
        //TODO: Whatever you need
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接