单击listview项目上的长按时删除列表视图的项目

时间:2014-04-16 12:01:49

标签: java android google-maps listview android-listview

我正在开发一个应用程序,因为我正在使用谷歌地图v2,我将五个地址位置保存为arraylist.i形式的共享偏好使用listview显示5地址。现在我想要从列表视图中删除该项目什么时候我长按特定项目。因为我在listview上使用'setOnItemLongClickListener()'。

这里我需要从sharedpreference获取数组并删除我要删除的特定项目,我尝试如下。但它不能正常工作。请任何帮助

protected void removeItemFromList(int position) {
        final int deletePosition = position;


                    if(addressList.size()>0){
                    addressList.remove(deletePosition);
                    }
                    if(addAList.size()>0){
                   addAList.remove(deletePosition);
                    }
                    adapter.remove(deletePosition);
                    adapter1.remove(deletePosition);
                    adapter.notifyDataSetChanged();
                    adapter.notifyDataSetInvalidated();
                    adapter1.notifyDataSetChanged();
                    adapter1.notifyDataSetInvalidated();

            }
        });

我的代码

GoogleMap _googlemap;
private LatLng hydLocation;
Button clearButton;
private SharedPreferences sharedPreferences;
private Editor editor;
private double lat;
private double lng;
public static ArrayList<String>  addressList = new ArrayList<String>();;
public static ArrayList<String> distanceList = new ArrayList<String>();;
public static ArrayList<LatLng> latLngList = new ArrayList<LatLng>();;
public ListView addressListView;
public static ArrayList<Marker> markerList = new ArrayList<Marker>();;
public static ArrayList<Float> latArray = new ArrayList<Float>(); ;
public static ArrayList<Float> lngArray = new ArrayList<Float>();;
private String[] addressArry;
private static int count=0;
private Builder alertDialogBuilder;
private EditText input;
protected String diskm;
private String distance;
private Marker marker1;
private Marker marker2;
private Marker marker3;
private Marker marker4;
private Marker marker5;
private Float lng1;
private Float lat1;
private ArrayAdapter adapter;
private ArrayAdapter adapter1;
private LatLng latLng;
public static ArrayList<String> addAList=new ArrayList<String>();
public static ArrayList<Float> lngList= new ArrayList<Float>();
public static ArrayList<Float> latList= new ArrayList<Float>();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_or_delete_favourate_loc);
    addressListView =(ListView)findViewById(R.id.listView);

    clearButton = (Button)findViewById(R.id.clearBtn);
    _googlemap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(
            R.id.favarouteLocMap)).getMap(); 
    _googlemap.getUiSettings().setZoomControlsEnabled(true);
    _googlemap.getUiSettings().setCompassEnabled(true);
    _googlemap.getUiSettings().setMyLocationButtonEnabled(true);
    hydLocation = new LatLng(17.3752800, 78.4744400);
    _googlemap.moveCamera(CameraUpdateFactory.newLatLngZoom(hydLocation, 10));
    _googlemap.setOnMapClickListener(this);
     sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    editor = sharedPreferences.edit();
    editor.clear();


     /*addAList=new ArrayList<String>();
    latList = new ArrayList<Float>();
     lngList = new ArrayList<Float>();*/
    int size1=sharedPreferences.getInt("size1",0);
    int size2=sharedPreferences.getInt("size2",0);
    int size3=sharedPreferences.getInt("size3",0);

    for(int j=0;j<size1;j++)
    {
        addAList.add(sharedPreferences.getString("addr"+j,""));
    }


     adapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,addAList);
     addressListView.setAdapter(adapter);

     for(int j=0;j<size2;j++){
         latList.add(sharedPreferences.getFloat("latArr"+j,0.0f));
     }
     Log.e("LAT", ""+latList.size());

     for(int j=0;j<size3;j++){
         lngList.add(sharedPreferences.getFloat("lngArr"+j,0.0f));
     }

     for(int i=0;i<latList.size();i++){
          lat1=latList.get(i);
          lng1=lngList.get(i);
          Log.e("LAT LNG", ""+lat1+lng1);
         latLng = new LatLng((double)lat1,(double)lng1);
         getMarks(_googlemap, latLng);
     }
     addressListView.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                int pos, long arg3) {
            // TODO Auto-generated method stub
            Toast.makeText(getApplicationContext(), ""+pos, 100).show();

                    removeItemFromList(pos);



            return false;
        }
    });
}

@Override
public void onMapClick(final LatLng point) {
    // TODO Auto-generated method stub
     lat = point.latitude;
     lng = point.longitude;
     count=sharedPreferences.getInt("count",0);
     count++;

     editor.clear();
    Geocoder geoCoder = new Geocoder(AddOrDeleteFavourateLocActivity.this, Locale.getDefault());
    try{
         List<Address> addresses = geoCoder.getFromLocation(point.latitude, point.longitude, 1);
         if (addresses != null) {
             Address returnedAddress = addresses.get(0);
             StringBuilder strReturnedAddress = new StringBuilder("");

             for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
                 strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
             }
             final String strAdd = strReturnedAddress.toString();

             alertDialogBuilder = new AlertDialog.Builder(
                    AddOrDeleteFavourateLocActivity.this);
            alertDialogBuilder.setTitle("Enter Distance From Your Location");
            input = new EditText(AddOrDeleteFavourateLocActivity.this);
            input.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
            alertDialogBuilder.setView(input);
            alertDialogBuilder.setPositiveButton("OK",new DialogInterface.OnClickListener() {



                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    distance=input.getText().toString();
                     diskm ="\n"+distance+" km";
                     if(count==1){

                         addressList.add(strAdd+diskm);
                         latLngList.add(point);
                         markerList.add(marker1);
                         latArray.add((float)lat);
                         lngArray.add((float)lng);
                         editor.putInt("count", count);
                         distanceList.add((String)distance);
                         Log.e("DIST", distance);


                     }
                     if(count==2){

                         addressList.add(strAdd+diskm);
                         latLngList.add(point);
                         markerList.add(marker2);
                         latArray.add((float)lat);
                         lngArray.add((float)lng);
                         editor.putInt("count", count);
                         distanceList.add((String)distance);
                     }
                     if(count==3){

                         addressList.add(strAdd+diskm);
                         latLngList.add(point);
                         markerList.add(marker3);
                         latArray.add((float)lat);
                         lngArray.add((float)lng);
                         editor.putInt("count", count);
                         distanceList.add((String)distance);

                     }
                     if(count==4){

                         addressList.add(strAdd+diskm);
                         latLngList.add(point);
                         markerList.add(marker4);
                         latArray.add((float)lat);
                         lngArray.add((float)lng);
                         editor.putInt("count", count);
                         distanceList.add((String)distance);

                     }
                     if(count==5){

                         addressList.add(strAdd+diskm);
                         latLngList.add(point);
                         markerList.add(marker5);
                         latArray.add((float)lat);
                         lngArray.add((float)lng);
                         editor.putInt("count", count);
                         distanceList.add((String)distance);
                     }
                     adapter1=new ArrayAdapter(AddOrDeleteFavourateLocActivity.this,android.R.layout.simple_list_item_1,addressList);
                     addressListView.setAdapter(adapter1);

                   for(int i=0;i<distanceList.size();i++){
                       editor.putString("dist"+i, distanceList.get(i));
                   }
                   editor.putInt("distSize", distanceList.size());

                   for(int i=0;i<addressList.size();i++)
                     {
                       editor.putString("addr"+i,addressList.get(i));
                     }
                     for(int i=0;i<latArray.size();i++)
                     {
                       editor.putFloat("latArr"+i,latArray.get(i));
                     }
                     for(int i=0;i<lngArray.size();i++)
                     {
                       editor.putFloat("lngArr"+i,lngArray.get(i));
                     }
                     editor.putInt("size1",addressList.size());
                     editor.putInt("size2",latArray.size());
                     editor.putInt("size3",lngArray.size());

                    editor.commit();


                }

            });
            alertDialogBuilder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    --count;

                    marker1.remove();


                }
            });

             if(count==1){
                 marker1= getMarks(_googlemap, point);
                alertDialogBuilder.show();



             }
             if(count==2){
                  marker1=getMarks(_googlemap, point);
                  alertDialogBuilder.show();

             }
             if(count==3){
                  marker1=getMarks(_googlemap, point);
                  alertDialogBuilder.show();


             }
             if(count==4){
                  marker1=getMarks(_googlemap, point);
                  alertDialogBuilder.show();


             }
             if(count==5){
                 marker1=getMarks(_googlemap, point);
                 alertDialogBuilder.show();


             }
             if(count>5){
                 Toast.makeText(getApplicationContext(),"Sorry You Can Add Only Five Locations", 100).show();
             }



         }
    }
    catch(Exception e){
        e.printStackTrace();
    }

}
private Marker getMarks(GoogleMap googleMap,LatLng arg0){
    Marker marker;
     MarkerOptions markerOption = new MarkerOptions();
    markerOption.position(arg0).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)).flat(true);
    markerOption.draggable(true);

     marker=googleMap.addMarker(markerOption);
     return marker;
}
public void clearData(View v){
    _googlemap.clear();
    //marker1.remove();
    sharedPreferences.edit().remove("size2").commit();
    sharedPreferences.edit().remove("size3").commit();

    editor.clear();
    editor.commit();
    adapter.clear();
    if(!addAList.isEmpty()){
        addAList.clear();}
    if(!latList.isEmpty()){
        latList.clear();
    }
    if(!lngList.isEmpty()){
        lngList.clear();
    }
}


 protected void removeItemFromList(int position) {
        final int deletePosition = position;

        AlertDialog.Builder alert = new AlertDialog.Builder(
                AddOrDeleteFavourateLocActivity.this);

        alert.setTitle("Delete");
        alert.setMessage("Do you want delete this item?");
        alert.setPositiveButton("YES", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TOD O Auto-generated method stub

                    // main code on after clicking yes
                    if(addressList.size()>0){
                    addressList.remove(deletePosition);
                    }
                    if(addAList.size()>0){
                   addAList.remove(deletePosition);
                    }
                    adapter.remove(deletePosition);
                    adapter1.remove(deletePosition);
                    adapter.notifyDataSetChanged();
                    adapter.notifyDataSetInvalidated();
                    adapter1.notifyDataSetChanged();
                    adapter1.notifyDataSetInvalidated();
                    /*Intent intent = new Intent(AddOrDeleteFavourateLocActivity.this,AddOrDeleteFavourateLocActivity.class);
                    startActivity(intent);*/

            }
        });
        alert.setNegativeButton("CANCEL", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                dialog.dismiss();
            }
        });

        alert.show();

    }

3 个答案:

答案 0 :(得分:0)

我建议将项目保存在ArrayList的List适配器中。同样在适配器创建方法中,如下所示:

public void removeItem(int pPosition) {
    items.remove(pPosition);
    notifyDatasetChanged();
}

在activity / fragment中包含对适配器的引用。 实现ListView的方法setOnItemClickListener&amp; setOnItemLongClickListener。

答案 1 :(得分:0)

您可以使用以下简单的代码行。

yourItems.remove(poss);
yourAdapter.clear();
yourListView.setAdapter(yourAdapter);

答案 2 :(得分:0)

在这种情况下,您应该实现这些活动方法

onSaveInstanceState(Bundle pInstanceState)
onRestoreInstanceState(Bundle pInstanceState)

使您的适配器可序列化(或Parcelable)。在onSaveInstanceState中将它作为Extra传递给Bundle。

之后在Activity的onResume中调用onRestoreInstanceState,在那里你将从extras中检索和设置适配器。 在Activity的onPause中调用onSaveInstanceState。

希望这会有所帮助:)