2013-10-24 122 views
4

我已經實現了ActionBarSherlockSupportMapFragment的指導this接受的答案的問題。一切運作良好。但唯一的問題是onOptionsItemSelected方法被調用兩次。這裏是代碼 -android-onOptionsItemSelected方法被調用兩次

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

編輯 -

這是我的整個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; 
    } 
} 

}

+0

你可以發佈你的全班同時呢? –

+0

@YeLinAung發表。 – Naddy

+0

您的基本活動在您的基本活動中是否有另一個「onOptionsItemSelected」?或者也許你可以嘗試刪除'setHasOptionsMenu(true); 'onResume' –

回答

3

在你onOptionsItemSelected方法不調用在超類的方法end

return super.onOptionsItemSelected(item); 

返回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; 
} 
+0

執行此操作後,菜單項消失。 – Naddy

+0

嘗試添加一個默認case..check編輯答案 –

+1

仍然沒有區別。菜單項沒有出現。 – Naddy

0

我有同樣的問題。 什麼工作對我來說:

更換

return super.onOptionsItemSelected(item); 

return true; 

,不要使在onOptionsItemSelected超級調用。 我希望這對你也有效。

+3

接受的答案也一樣。有什麼要重複它? – Naddy