当前位置: 首页 > 知识库问答 >
问题:

未调用onOptionsItemClick或onMenuItemClick

滕星纬
2023-03-14

问题是onMenuItemClick的输入参数为(View v,int position),而我不能将其仅改为(View v)或(MenuItem item)。

我想要的是点击菜单中的每一项都应该带出新的活动!

我还尝试将所有的开关大小写中断语句放入OOptionSitemSelected方法,但它仍然不起作用!

(已弃用)未调用onOptionsItemSelected片段

下面是activity_main_menu.xml布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@color/menu_item_background">

    <include layout="@layout/toolbar" />

    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

下面是fragment_main.xml布局

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.android.coffeeshop.MainFragment">


    <!-- TODO: Update blank fragment layout -->
    <LinearLayout

        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:background="@color/menu_item_background">

        <EditText
            android:id="@+id/username"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:cursorVisible="true"
            android:hint="@string/EditTextHint"
            android:inputType="textNoSuggestions" />

        <EditText
            android:id="@+id/usercontact"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:cursorVisible="true"
            android:hint="@string/usercontactHint"
            android:inputType="textNoSuggestions" />

        <EditText
            android:id="@+id/useremail"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:cursorVisible="true"
            android:hint="@string/useremailHint"
            android:inputType="textEmailAddress" />


        <TextView
            style="@style/HeaderTextStyle"
            android:layout_marginTop="16dp"
            android:text="@string/Toppings" />


        <CheckBox
            android:id="@+id/whippedCreamcheckbox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:paddingEnd="24dp"
            android:paddingLeft="24dp"
            android:paddingStart="24dp"
            android:text="@string/WhippedCream"
            android:textSize="16sp" />

        <CheckBox
            android:id="@+id/Chocolatebox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:paddingEnd="24dp"
            android:paddingLeft="24dp"
            android:paddingStart="24dp"
            android:text="@string/Chocolate"
            android:textSize="16sp" />


        <TextView
            style="@style/HeaderTextStyle"
            android:layout_marginTop="16dp"
            android:text="@string/quantity" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">


            <Button
                android:layout_width="48dp"
                android:layout_height="48dp"
                android:layout_marginTop="16dp"
                android:onClick="decrement"
                android:text="@string/minus" />

            <TextView
                android:id="@+id/quantity_text_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="8dp"
                android:layout_marginRight="8dp"
                android:layout_marginTop="16dp"
                android:text="@string/Zero"
                android:textColor="@android:color/black"
                android:textSize="20sp" />

            <Button
                android:layout_width="48dp"
                android:layout_height="48dp"
                android:layout_marginTop="16dp"
                android:onClick="increment"
                android:text="@string/plus" />


        </LinearLayout>

        <TextView
            style="@style/HeaderTextStyle"
            android:layout_marginTop="16dp"
            android:text="@string/OrderSummary" />

        <TextView
            android:id="@+id/order_summary_text_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:text="@string/Price"
            android:textColor="@android:color/black"
            android:textSize="20sp" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <Button
                android:id="@+id/orderButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="16dp"
                android:onClick="submitOrder"
                android:text="@string/Order" />

            <Button
                android:id="@+id/placeOrder"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="16dp"
                android:layout_marginStart="16dp"
                android:layout_marginTop="16dp"
                android:onClick="placeOrder"
                android:text="@string/PlaceOrder" />


        </LinearLayout>

    </LinearLayout>

</ScrollView>
    package com.example.android.coffeeshop5profile;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.ActionMenuView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.yalantis.contextmenu.lib.ContextMenuDialogFragment;
import com.yalantis.contextmenu.lib.MenuObject;
import com.yalantis.contextmenu.lib.MenuParams;
import com.yalantis.contextmenu.lib.interfaces.OnMenuItemLongClickListener;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * This app displays an order form to order coffee.
 */

public class MainMenu extends AppCompatActivity implements ActionMenuView.OnMenuItemClickListener, OnMenuItemLongClickListener {

    private FragmentManager fragmentManager;
    private ContextMenuDialogFragment mMenuDialogFragment;
    int quantity = 1;
    int price = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_menu);
        fragmentManager = getSupportFragmentManager();
        initToolbar();
        initMenuFragment();
        addFragment(new MainFragment(), true, R.id.container);

    }

    private void initMenuFragment() {
        MenuParams menuParams = new MenuParams();
        menuParams.setActionBarSize((int) getResources().getDimension(R.dimen.tool_bar_height));
        menuParams.setMenuObjects(getMenuObjects());
        menuParams.setClosableOutside(false);
        mMenuDialogFragment = ContextMenuDialogFragment.newInstance(menuParams);

        mMenuDialogFragment.setItemLongClickListener(this);
    }

    private List<MenuObject> getMenuObjects() {

        List<MenuObject> menuObjects = new ArrayList<>();

        MenuObject close = new MenuObject();
        close.setResource(R.drawable.icn_close);

        MenuObject send = new MenuObject("Send message");
        send.setResource(R.drawable.icn_1);

        MenuObject like = new MenuObject("Like profile");
        Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.icn_2);
        like.setBitmap(b);

        MenuObject addFr = new MenuObject("Add to friends");
        BitmapDrawable bd = new BitmapDrawable(getResources(),
                BitmapFactory.decodeResource(getResources(), R.drawable.icn_3));
        addFr.setDrawable(bd);

        MenuObject addFav = new MenuObject("Add to favorites");
        addFav.setResource(R.drawable.icn_4);

        MenuObject block = new MenuObject("Block user");
        block.setResource(R.drawable.icn_5);

        menuObjects.add(close);
        menuObjects.add(send);
        menuObjects.add(like);
        menuObjects.add(addFr);
        menuObjects.add(addFav);
        menuObjects.add(block);
        return menuObjects;
    }

    private void initToolbar() {
        Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
        TextView mToolBarTextView = (TextView) findViewById(R.id.text_view_toolbar_title);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        mToolbar.setNavigationIcon(R.drawable.btn_back);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mToolBarTextView.setText(R.string.title_text);
    }


    protected void addFragment(Fragment fragment, boolean addToBackStack, int containerId) {
        invalidateOptionsMenu();
        String backStackName = fragment.getClass().getName();
        boolean fragmentPopped = fragmentManager.popBackStackImmediate(backStackName, 0);
        if (!fragmentPopped) {
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            transaction.add(containerId, fragment, backStackName)
                    .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
            if (addToBackStack)
                transaction.addToBackStack(backStackName);
            transaction.commit();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.context_main_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.context_menu:
                if (fragmentManager.findFragmentByTag(ContextMenuDialogFragment.TAG) == null) {
                    mMenuDialogFragment.show(fragmentManager, ContextMenuDialogFragment.TAG);
                }
                break;
            case R.drawable.icn_3:

                Intent userProfileIntent = new Intent(MainMenu.this, UserProfile.class);

                MainMenu.this.startActivity(userProfileIntent);

                break;

            case R.drawable.icn_4:

                Intent wishListIntent = new Intent(MainMenu.this, UserProfile.class);

                MainMenu.this.startActivity(wishListIntent);

                break;

        }
        return false; //Turning this true or to super.OnOptionsItemSelected did nothing!

    }

    @Override
    public void onBackPressed() {
        if (mMenuDialogFragment != null && mMenuDialogFragment.isAdded()) {
            mMenuDialogFragment.dismiss();
        } else {
            finish();
        }
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {

        switch (item.getItemId()){

            case R.drawable.icn_3:

                Intent userProfileIntent = new Intent(MainMenu.this, UserProfile.class);

                MainMenu.this.startActivity(userProfileIntent);

                break;

            case R.drawable.icn_4:

                Intent wishListIntent = new Intent(MainMenu.this, UserProfile.class);

                MainMenu.this.startActivity(wishListIntent);

                break;

        } return true;
    }

    @Override
    public void onMenuItemLongClick(View clickedView, int position) {
        Toast.makeText(this, "Long clicked on position: " + position, Toast.LENGTH_SHORT).show();
    }


    public void submitOrder(View view) {

        String orderSummaryString = createOrderSummary(quantity);

        displayMessage(orderSummaryString);

    }

    public void placeOrder(View view) {

        TextView useremail = (TextView) findViewById(R.id.useremail);

        String useremailString = useremail.getText().toString();

        String orderSummaryString = createOrderSummary(quantity);

        sendMail(useremailString, "Coffee Order By: " + useremailString, orderSummaryString);

    }

    private void sendMail(String email, String subject, String messageBody) {
        Session session = createSessionObject();

        try {
            Message message = createMessage(email, subject, messageBody, session);
            new SendMailTask().execute(message);
        } catch (MessagingException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    private Message createMessage(String email, String subject, String messageBody, Session session)
            throws MessagingException, UnsupportedEncodingException {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("clientaddress@gmail.com", "Coffee Order By"));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(email, email));
        message.setSubject(subject);
        message.setText(messageBody);
        return message;
    }

    private Session createSessionObject() {
        Properties properties = new Properties();
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.host", "smtp.gmail.com");
        properties.put("mail.smtp.port", "587");

        return Session.getInstance(properties, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("clientaddress@gmail.com", "************");
            }
        });
    }

    public class SendMailTask extends AsyncTask<Message, Void, Void> {
        private ProgressDialog progressDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = ProgressDialog.show(MainMenu.this, "Please wait", "Sending mail", true, false);
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            progressDialog.dismiss();
        }

        @Override
        public Void doInBackground(Message... messages) {
            try {
                Transport.send(messages[0]);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }


    /**
     * This method is called when the plus button is clicked.
     */

    public void increment(View view) {

        if (quantity < 100) {
            quantity = quantity + 1;
            displayQuantity(quantity);
        } else {
            Toast.makeText(this, "You have reached maximum numbers of coffees to be allowed!", Toast.LENGTH_SHORT).show();
        }

    }

    /**
     * This method is called when the minus button is clicked.
     */

    public void decrement(View view) {

        if (quantity >= 2) {
            quantity = quantity - 1;
            displayQuantity(quantity);
        } else {
            Toast.makeText(this, "You can not place order in negative number!", Toast.LENGTH_SHORT).show();
        }
    }


    public String createOrderSummary(int quantity) {
        CheckBox whippedCreamCheckbox = (CheckBox) findViewById(R.id.whippedCreamcheckbox);
        boolean hasWhippedCream = whippedCreamCheckbox.isChecked();


        CheckBox chocolatebox = (CheckBox) findViewById(R.id.Chocolatebox);
        boolean hasChocolate = chocolatebox.isChecked();

        price = 5;

        if (hasWhippedCream) {
            price = price + 1;
        }
        if (hasChocolate) {
            price = price + 2;
        }

        int finalPrice = quantity * price;

        EditText usernameTextView = (EditText) findViewById(R.id.username);
        String usernameString = usernameTextView.getText().toString();

        EditText usercontact = (EditText) findViewById(R.id.usercontact);
        String userContactString = usercontact.getText().toString();

        EditText useremail = (EditText) findViewById(R.id.useremail);
        String userEmailString = useremail.getText().toString();

        String OrderSummary = getString(R.string.username) + ": " + usernameString;
        OrderSummary += "\n" + getString(R.string.ContactNumber) + " " + userContactString;
        OrderSummary += "\n" + getString(R.string.eAddress) + " " + userEmailString;
        OrderSummary += "\n" + getString(R.string.AddedWhippedCream) + " " + hasWhippedCream;
        OrderSummary += "\n" + getString(R.string.AddedChocolate) + " " + hasChocolate;
        OrderSummary += "\n" + getString(R.string.quantity) + ": " + quantity;
        OrderSummary += "\n" + getString(R.string.totalprice) + finalPrice;
        OrderSummary += "\n" + getString(R.string.thankyou);
        return OrderSummary;
    }

    /**
     * This method displays the given quantity value on the screen.
     */
    public void displayQuantity(int number) {
        TextView quantityTextView = (TextView) findViewById(
                R.id.quantity_text_view);
        quantityTextView.setText(String.format("%d", number));
    }

    /**
     * This method displays the given text on the screen.
     */
    public void displayMessage(String message) {
        TextView orderSummaryTextView = (TextView) findViewById(R.id.order_summary_text_view);
        orderSummaryTextView.setText(message);
    }
}
package com.example.android.coffeeshop5profile;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


public class MainFragment extends Fragment {


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        setHasOptionsMenu(true);
        setMenuVisibility(false);
        return rootView;
    }

}

下面是activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/blue_grey_700"
    android:orientation="vertical"
    android:weightSum="4"
    tools:context=".legacy.MainActivity">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="3"
        android:gravity="center_vertical"
        android:orientation="vertical">


        <ImageView
            android:id="@+id/google_icon"
            android:layout_width="48dp"
            android:layout_height="48dp"
            android:layout_gravity="center"

            android:layout_marginBottom="10dp"
            android:contentDescription="@string/desc_google_icon"
            android:src="@drawable/googleg_color" />


        <TextView
            android:id="@+id/title_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:layout_gravity="center"
            android:text="@string/title_text"
            android:textColor="@android:color/white"
            android:textSize="36sp" />


        <TextView
            android:id="@+id/status"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="@string/signed_out"
            android:textColor="@android:color/white"
            android:textSize="14sp" />


        <TextView
            android:id="@+id/detail"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:fadeScrollbars="true"
            android:gravity="center"
            android:maxLines="5"
            android:padding="10dp"
            android:scrollbars="vertical"
            android:textColor="@android:color/white"
            android:textSize="14sp" />


    </LinearLayout>


    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="@color/blue_grey_900">


        <com.google.android.gms.common.SignInButton
            android:id="@+id/sign_in_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:visibility="visible"
            tools:visibility="gone" />


        <LinearLayout
            android:id="@+id/sign_out_and_disconnect"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:orientation="horizontal"
            android:paddingLeft="16dp"
            android:paddingRight="16dp"
            android:visibility="gone"
            tools:visibility="visible">


            <Button
                android:id="@+id/sign_out_button"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/sign_out"
                android:theme="@style/ThemeOverlay.MyDarkButton" />


            <Button
                android:id="@+id/disconnect_button"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/disconnect"
                android:theme="@style/ThemeOverlay.MyDarkButton" />
            <Button
                android:id="@+id/secondpage"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/secondpage"
                android:theme="@style/ThemeOverlay.MyDarkButton" />

        </LinearLayout>


    </RelativeLayout>


</LinearLayout>

下面是res/menu/context_main_menu.xml文件

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/context_menu"
        android:title="@string/context_menu"
        android:icon="@drawable/btn_add"
        android:orderInCategory="100"
        app:showAsAction="always" />



</menu>

...不幸的是,已经达到了30000个字符的限制,所以我无法上传mainactivity.java文件!

共有1个答案

朱令
2023-03-14

请在上尝试此代码

更改以下代码

onMenuItemClick(MenuItem item)

onMenuItemClick(View clickedView, int position)
`@override
public void onMenuItemClick(View clickedView, int position) {

    switch (position) {
        case 1:
            startActivity(new Intent(MainActivity.this, UserProfile.class));
            break;
        case 2:
            startActivity(new Intent(MainActivity.this, UserProfile.class));
            break;
    }
}`
 类似资料:
  • 问题内容: 我有以下电话,它根本无法在ie7或8中工作-但在其他所有方面都完美! 我也尝试了以下方法(向URL添加随机数),但未能解决问题: 任何有关如何使它起作用的想法,因为它是页面的重要组成部分。 问题答案: 发现了问题…我发现这是一个虚假的HTML引起了问题,真是不真实!

  • 问题内容: 我正在开发具有以下功能的条形码扫描应用程序: •访问设备相机,在SurfaceView上预览相机,并自动重新对焦 •Attemtps使用两种方法解码条形码 a)在使用 onTouchEvent(MotionEvent event)的 SurfaceView touch上,尝试拍摄条形码的图片,但获取 java.lang.RuntimeException:takePicture失败 b)

  • 两天以来,我试图让一个UtteranceProgressListener工作。我尝试了很多来自Stackoverflow和其他网站的代码--没有一个对我有效。下面是我当前的代码:

  • 我正在开发一个带有ActionBars的应用程序,它支持姜饼和其他功能。所以基本上我在使用支持库并扩展 行动B活动 对于我所有的活动。除了 onSupportNavigateUp() 方法。它只是不被调用在留档中所述。 每当用户选择从操作栏在应用程序的活动层次结构中向上导航时,就会调用此方法。 这很容易,但我一直不明白为什么它不能像预期的那样工作,谷歌也帮不上忙。这是虫子吗?还是我错过了什么?

  • 运行playstore Build Apk时,未调用Marshmallow Runtime Permissions onRequestPermissionsResult,但正常调试Apk时运行良好。谁来帮帮我。。谢谢 OnRequestPermissionResult方法

  • 我很难让正常工作。无论我怎么努力,我都不能让它被称为。 我的应用程序的体系结构如下所示:我的主活动包含一个片段,其中包含一个ViewPager,而ViewPager又有四个子片段实例。目前,我正在(成功地)用填充活动中的初始选项菜单,但我希望添加一些对应于每个活动子片段的额外选项。 如果有人知道这里发生了什么,我会非常感激,因为我已经被困在这个问题上两天了。 更新--我已经搞清楚了现在的问题是什么