Android的onOptionsItemSelected方法调用了两次 [英] android-onOptionsItemSelected method called twice

查看:175
本文介绍了Android的onOptionsItemSelected方法调用了两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已实施 ActionBarSherlock SupportMapFragment 为指导的<一个公认的答案href="http://stackoverflow.com/questions/13721929/using-actionbarsherlock-with-the-new-supportmapfragment">this题。一切都运行良好。但唯一的问题是, onOptionsItemSelected 方法获取调用两次。这里是code -

I have implemented ActionBarSherlock with the SupportMapFragment as guided by the accepted answer of this question. Everything works well. But the only problem is that the onOptionsItemSelected method is getting called twice. Here is the code-

@Override
public boolean onOptionsItemSelected(
        com.actionbarsherlock.view.MenuItem item) {
    switch (item.getItemId()) {
 case R.id.navigation:
 Log.d("tag","text");
 break;
 }
 return super.onOptionsItemSelected(item);
}

编辑 -

EDIT-

这是我的整个 FragmentMaps 类:

package com.vishalaksh.technex;

import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.CancelableCallback;
import com.google.android.gms.maps.UiSettings;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.vishalaksh.technex.db.DatabaseHelper;
import com.vishalaksh.technex.db.DbConstants;
import com.vishalaksh.technex.utils.Constants;
import com.vishalaksh.technex.utils.JSONconstants;
import com.vishalaksh.technex.utils.MapConstants;
import com.vishalaksh.technex.utils.SherlockMapFragment;

public class FragmentMaps extends SherlockMapFragment implements MapConstants,
        Constants, DbConstants, JSONconstants {

private GoogleMap mMap;
private static final int VIEW = 0;
DatabaseHelper db;

public FragmentMaps() {
    super();

}

public static FragmentMaps newInstance() {
    FragmentMaps frag = new FragmentMaps();

    return frag;
}

@Override
public View onCreateView(LayoutInflater arg0, ViewGroup arg1, Bundle arg2) {
    View v = super.onCreateView(arg0, arg1, arg2);

    db = new DatabaseHelper(getActivity());

    setUpMapIfNeeded();
    return v;
}

public void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the
    // map.
    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        mMap = getMap();
        // Check if we were successful in obtaining the map.
        if (mMap != null) {
            setUpMap();
        }
    }
}

private void setUpMap() {
    UiSettings settings = mMap.getUiSettings();
    settings.setAllGesturesEnabled(true);
    settings.setMyLocationButtonEnabled(true);
    mMap.setMyLocationEnabled(true);
    mMap.moveCamera(CameraUpdateFactory.newCameraPosition(BHU_position));

    GoToIITBHU();

    /*
     * the following block shifted to onresume() if
     * (getActivity().getComponentName().getClassName()
     * .equalsIgnoreCase(Activity_msg_map.class.getName())) { //
     * Activity_msg_map setupMsgMap(); } else { // activity main
     * setupMain(); setHasOptionsMenu(true); }
     */

}

@Override
public void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    if (mMap != null) {
        if (getActivity().getComponentName().getClassName()
                .equalsIgnoreCase(Activity_msg_map.class.getName())) {
            // Activity_msg_map
            setupMsgMap();
        } else {
            // activity main
            setupMain();
            setHasOptionsMenu(true);
        }
    }

}

private boolean checkReady() {
    if (mMap == null) {
        Toast.makeText(getActivity(), R.string.map_not_ready,
                Toast.LENGTH_SHORT).show();
        return false;
    }
    return true;
}

@Override
public void onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu,
        com.actionbarsherlock.view.MenuInflater inflater) {
    // menu.add(VIEW, VIEW_PLACES_MENU_ITEM, 0,
    // "View Places").setShowAsAction(
    // MenuItem.SHOW_AS_ACTION_ALWAYS|MenuItem.SHOW_AS_ACTION_WITH_TEXT);
    // menu.add(VIEW, VIEW_EVENTS_MENU_ITEM, 0,
    // "View Events").setShowAsAction(
    // MenuItem.SHOW_AS_ACTION_ALWAYS|MenuItem.SHOW_AS_ACTION_WITH_TEXT);
    menu.clear();

    SubMenu optionsMenu = menu.addSubMenu("View");

    optionsMenu.add(VIEW, VIEW_PLACES_MENU_ITEM, 0, "View Places");
    optionsMenu.add(VIEW, VIEW_EVENTS_MENU_ITEM, 1, "View Events");

    // TODO import mdpi n other resources
    MenuItem subMenu1Item = optionsMenu.getItem();
    subMenu1Item.setIcon(R.drawable.ic_action_view).setShowAsAction(
            MenuItem.SHOW_AS_ACTION_ALWAYS
                    | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
    super.onCreateOptionsMenu(menu, inflater);
}

@Override
public boolean onOptionsItemSelected(
        com.actionbarsherlock.view.MenuItem item) {
    switch (item.getItemId()) {

    case VIEW_PLACES_MENU_ITEM:
        Toast.makeText(getActivity(), EXTRA_EVENT_CATEGORY, Toast.LENGTH_SHORT).show();//This toast is displayed two times.
        // TODO clear markers if any
        clearmarkers();
        // TODO put place markers
        PreferenceManager.getDefaultSharedPreferences(getActivity()).edit()
                .putInt(PREF_MAP_VIEW, VIEW_LOC).commit();
        putLocationMarkers();
        break;
    case VIEW_EVENTS_MENU_ITEM:
        // TODO clear markers if any
        clearmarkers();
        // TODO put event markers
        PreferenceManager.getDefaultSharedPreferences(getActivity()).edit()
                .putInt(PREF_MAP_VIEW, VIEW_EVENT).commit();
        putEventMarkers();
        break;
    }
    return super.onOptionsItemSelected(item);
}

private void putEventMarkers() {
    // get all the locations which have events
    Cursor cLocation = db.getReadableDatabase().query(tableEventsName,
            new String[] { colForeignLocationsNameTableEvent }, null, null,
            colForeignLocationsNameTableEvent, null, null);

    if (cLocation.getCount() == 0) {
        Log.d(TAG, "cLocation.getCount()==0");
        return;
    } else {
        Log.d(TAG, "total " + cLocation.getCount()
                + " locations found having events...");
    }

    cLocation.moveToFirst();
    do {
        // get each location name
        String location = cLocation.getString(cLocation
                .getColumnIndexOrThrow(colForeignLocationsNameTableEvent));
        // get the details of this location
        Cursor cLocationDetails = db.getReadableDatabase().query(
                tableLocationsName, null, colNameTableLocations + " =? ",
                new String[] { location }, null, null, null);

        if (cLocationDetails.getCount() != 1) {
            Log.w(TAG,
                    "no. of locations in cursor cLocationDetails in FragmentMaps is not 1!, its:"
                            + cLocationDetails.getCount());
        }

        cLocationDetails.moveToFirst();
        double lat = cLocationDetails.getDouble(cLocationDetails
                .getColumnIndexOrThrow(colLatTableLocations));
        double lng = cLocationDetails.getDouble(cLocationDetails
                .getColumnIndexOrThrow(colLongTableLocations));
        String title = cLocationDetails.getString(cLocationDetails
                .getColumnIndexOrThrow(colNameTableLocations));

        // get list of events for a particular location
        Cursor cEvent = db.getReadableDatabase().query(tableEventsName,
                null, colForeignLocationsNameTableEvent + " =? ",
                new String[] { location }, null, null, null);

        if (cEvent.getCount() == 0) {
            Log.e(TAG, "no events found for the location:" + location);
            /*
             * mMap.addMarker(new MarkerOptions().position( new LatLng(lat,
             * lng)).title(title));
             */} else {
            cEvent.moveToFirst();
            StringBuilder sb = new StringBuilder();
            do {
                sb.append(cEvent.getString(cEvent
                        .getColumnIndexOrThrow(colEventNameTableEvent)));
                sb.append(DELIMITER_SNIPPET);
            } while (cEvent.moveToNext());
            // delete last delimiter
            sb.delete(sb.lastIndexOf(DELIMITER_SNIPPET), sb.length() - 1);

            String snippet = sb.toString();

            mMap.addMarker(new MarkerOptions()
                    .position(new LatLng(lat, lng))
                    .title(getCorrectTitle(title))
                    .snippet(snippet)
                    .icon(BitmapDescriptorFactory
                            .defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)));

        }

    } while (cLocation.moveToNext());

}

private void putLocationMarkers() {

    /*
     * Cursor c = db.getReadableDatabase().query(tableLocationsName, null,
     * null, null, null, null, null);
     */
    Cursor c = db.getReadableDatabase().rawQuery(
            "SELECT * FROM " + tableLocationsName + " WHERE "
                    + colTrivialtableLocations + " !=?",
            new String[] { String.valueOf(TRIVIAL) });

    if (c.getCount() == 0) {
        Log.e(TAG, "cursor doesnt contain locations in FragmentMaps");
        return;
    }

    c.moveToFirst();
    do {
        double lat = c.getDouble(c
                .getColumnIndexOrThrow(colLatTableLocations));
        double lng = c.getDouble(c
                .getColumnIndexOrThrow(colLongTableLocations));
        String title = c.getString(c
                .getColumnIndexOrThrow(colNameTableLocations));
        String snippet = c.getString(c
                .getColumnIndexOrThrow(colSnippetTableLocations));
        mMap.addMarker(new MarkerOptions()
                .position(new LatLng(lat, lng))
                .title(getCorrectTitle(title))
                .snippet(snippet)
                .icon(BitmapDescriptorFactory
                        .defaultMarker(BitmapDescriptorFactory.HUE_RED)));

    } while (c.moveToNext());

}

@Override
public void onDestroy() {

    if (db != null) {
        db.close();
    }

    super.onDestroy();
}

private void clearmarkers() {

    mMap.clear();

}

private void setupMain() {
    clearmarkers();
    if (PreferenceManager.getDefaultSharedPreferences(getActivity())
            .getInt(PREF_MAP_VIEW, VIEW_LOC) == VIEW_LOC) {
        putLocationMarkers();
    } else {
        putEventMarkers();
    }

}

private void setupMsgMap() {
    String locname = getActivity().getIntent().getStringExtra(
            EXTRA_UPDATE_LOC);
    Log.d(TAG, "the location received by map is:" + locname);

    /*
     * Cursor c = db.getReadableDatabase().query(tableLocationsName, null,
     * colNameTableLocations + "=?", new String[] { locname }, null, null,
     * null);
     */

    Cursor c = db.getReadableDatabase().rawQuery(
            "SELECT * FROM " + tableLocationsName + " WHERE "
                    + colNameTableLocations + "=? LIMIT 1",
            new String[] { locname });

    if (c.getCount() != 1) {
        Log.e(TAG,
                "cursor doesnt contain single location in FragmentMaps it contains:"
                        + c.getCount());
        return;
    }
    c.moveToFirst();
    double lat = c.getDouble(c.getColumnIndexOrThrow(colLatTableLocations));
    double lng = c
            .getDouble(c.getColumnIndexOrThrow(colLongTableLocations));
    String title = c.getString(c
            .getColumnIndexOrThrow(colNameTableLocations));

    mMap.addMarker(new MarkerOptions()
            .position(new LatLng(lat, lng))
            .title(getCorrectTitle(title))
            .icon(BitmapDescriptorFactory
                    .defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)));

}

/**
 * Called when the Go To Bondi button is clicked.
 */
void GoToIITBHU() {
    if (!checkReady()) {
        return;
    }

    changeCamera(CameraUpdateFactory.newCameraPosition(IITBHU));
}

private void changeCamera(CameraUpdate update) {
    changeCamera(update, null);
}

/**
 * Change the camera position by moving or animating the camera depending on
 * the state of the animate toggle button.
 */
private void changeCamera(CameraUpdate update, CancelableCallback callback) {
    // boolean animated = ((CompoundButton)
    // findViewById(R.id.animate)).isChecked();
    if (true) {
        mMap.animateCamera(update, callback);
    } else {
        mMap.moveCamera(update);
    }
}

private String getCorrectTitle(String title) {
    if (title.equalsIgnoreCase(SBGround.NAME)) {
        return "Swatantrata Bhavan Ground";
    } else if (title.equalsIgnoreCase(SB.NAME)) {
        return "Swatantrata Bhavan";
    } else {
        return title;
    }
}

}

推荐答案

在你的 onOptionsItemSelected 方法并不在最后调用父类方法

In your onOptionsItemSelected method don't call super class method at the end

return super.onOptionsItemSelected(item);

而不是返回true。

Instead return true.

@Override
public boolean onOptionsItemSelected(
        com.actionbarsherlock.view.MenuItem item) {
    switch (item.getItemId()) {

    case VIEW_PLACES_MENU_ITEM:
        Toast.makeText(getActivity(), EXTRA_EVENT_CATEGORY, Toast.LENGTH_SHORT).show();//This toast is displayed two times.
        // TODO clear markers if any
        clearmarkers();
        // TODO put place markers
        PreferenceManager.getDefaultSharedPreferences(getActivity()).edit()
                .putInt(PREF_MAP_VIEW, VIEW_LOC).commit();
        putLocationMarkers();
        break;
    case VIEW_EVENTS_MENU_ITEM:
        // TODO clear markers if any
        clearmarkers();
        // TODO put event markers
        PreferenceManager.getDefaultSharedPreferences(getActivity()).edit()
                .putInt(PREF_MAP_VIEW, VIEW_EVENT).commit();
        putEventMarkers();
        break;

      default:
            return super.onOptionsItemSelected(item);
    }
    return true;
}

这篇关于Android的onOptionsItemSelected方法调用了两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆