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

问题描述 投票:3回答:7

我为菜单项创建了自定义布局。现在我需要它来点击时加载一个新的活动。代码逻辑如下:

资源中的菜单声明:

<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,我需要在片段内部的setHasOptionsMenu(true);方法中调用onCreateView,我已经这样做了。

现在在活动中,两个主要的重要方法,分别是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 android-layout android-fragments android-menu android-actionbaractivity
7个回答
1
投票

看看你的菜单项clickable应该是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" />

0
投票

我的应用程序遇到了同样的问题。正在创建操作栏但未响应点击。我以前在该活动上有相对布局,我将其更改为线性布局,并将小部件的大小和方向调整为以前的样子。它解决了我的问题。试试看。希望能帮助到你 :)


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
投票

因为您的活动的布局根GroupView可以阻止将点击事件分派到工具栏菜单项(如果您使用工具栏与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
    }

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所以如果你复制粘贴这段代码要小心。


0
投票

请试试吧

onCreateOptionsMenu(menu: Menu, inflater: MenuInflater)

方法

科特林

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");

它对我有用

© www.soinside.com 2019 - 2024. All rights reserved.