onOptionsItemClick或onMenuItemClick未被调用

时间:2016-03-08 21:02:53

标签: android menu fragment

(我要说清楚的第一件事就是我完全是NEWBIE,在android中非常初学者,实际上是编程/编码!)

菜单在onCreateOptionMenu中引用,调用方法也是onOptionsItemSelected打开菜单,但每个选项/项的方法设置为onMenuItemClick和onMenuItemLongClick,这是上下文菜单选项/项目的理想选择!

问题是onMenuItemClick将输入参数设置为(View v,int position),我无法将其更改为(View v)或(MenuItem item)。

我想要点击每个菜单项目应该带来新的活动!

我也尝试将所有switch-case-break语句放到onOptionsItemSelected方法中,但它仍然无效!

我也尝试过片段类,setHasOptionsMenu(true);但它不起作用!

onMenuItemClick doesn't get called

(Deprecated) Fragment onOptionsItemSelected not being called

以下是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>

下面是我试图处理片段菜单的MainMenu.java类文件!

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

下面是MainFragment.java类文件

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文件!

请帮忙! 最好的祝福, Sagar的

1 个答案:

答案 0 :(得分:0)

上试试这段代码

更改以下代码

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;
    }
}`

我希望这可以帮到你

相关问题