简体   繁体   English

如何在Android中从ListView正确删除项目?

[英]How do I properly remove an item from ListView in Android?

I have try to implement a delete procedure for my item inside the ListView, whe i call adapter.remove(itemToRemove); 我试图在ListView内为我的项目实现删除过程,因此我调用adapter.remove(itemToRemove);。 the itemToRemove is null, and no remove item appear... please Help me!, this is my code: itemToRemove为空,并且没有删除项出现...请帮助我,这是我的代码:

package com.bandweb.ordinefornitore; 包com.bandweb.ordinefornitore;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


import com.bandweb.ordinefornitore.adapter.CommentArrayAdapter;
import com.bandweb.ordinefornitore.datastructure.CommentObject;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.util.Log;
import android.view.Menu;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends Activity {

    private Spinner spin_prodotto, spin_tipo;
    private Button btnAggiungi,btnView_order,btnNew_order;
    private EditText EtQta;
    private TextView tvOrder;
    private String  Order,Msg;
    private ArrayList<CommentObject> commentList = null;
    private ListView commentListView = null;
    private Number Riga=0;
    public CommentArrayAdapter adapter;
    protected static final int DIALOG_REMOVE_CALC = 1;
    protected static final int DIALOG_REMOVE_PERSON = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main1);

         //Prepare the Dataset
        prepareDataList();

        commentListView = (ListView)findViewById(R.id.listComment);
        TextView emptyList = (TextView)findViewById(R.id.txtEmptyList);
        emptyList.setText("No comments to display!");
        commentListView.setEmptyView(emptyList);
        adapter = new CommentArrayAdapter(this, R.id.txtLoadingList, commentList);
        commentListView.setAdapter(adapter);

        //Manage the onItemClick method
        commentListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                    long id) {
                CommentObject currComment = (CommentObject)parent.getItemAtPosition(position);
                int duration = Toast.LENGTH_SHORT;
                Toast toast = Toast.makeText(MainActivity.this, 
                        "You clicked on a comment by "+currComment.senderName, duration);
                toast.show();

            }
        });

        commentListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener(){
            @Override
            public boolean  onItemLongClick(AdapterView<?> arg0, View v, int pos, long id) {
                // TODO Auto-generated method stub
                 return onLongListItemClick(v,pos,id);
            }

            protected boolean onLongListItemClick(View v, final int pos, long id) {
                final String str=commentListView.getItemAtPosition(pos).toString();
                Log.i("ListView", "onLongListItemClick stirng=" + str);

                AlertDialog diaBox = AskOption();
                diaBox.show();
                CommentObject itemToRemove = (CommentObject)v.getTag();
                adapter.remove(itemToRemove);
                adapter.notifyDataSetChanged();

                return false;
                }

        }); 

        addListenerOnButton();
    }




    public void removeProductOnClickHandler(View v) {

        AlertDialog diaBox = AskOption();
        diaBox.show();
        CommentObject itemToRemove = (CommentObject)v.getTag();
        adapter.remove(itemToRemove);
        adapter.notifyDataSetChanged();
    }

    private AlertDialog AskOption()
     {
        AlertDialog myQuittingDialogBox =new AlertDialog.Builder(this) 
            //set message, title, and icon
            .setTitle("Delete") 
            .setMessage(R.string.calculation_dialog_remove_text) 
            .setIcon(R.drawable.trash_empty)

            .setPositiveButton(R.string.calculation_dialog_button_ok, new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int whichButton) { 
                    //your deleting code

                    dialog.dismiss();
                }   

            })

            .setNegativeButton(R.string.calculation_dialog_button_cancel, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                    dialog.dismiss();

                }
            })
            .create();
            return myQuittingDialogBox;

        }   

//  private Dialog createDialogRemoveConfirm(final int dialogRemove) {
//      return new AlertDialog.Builder(getApplicationContext())
//      .setIcon(R.drawable.trash_empty)
//      .setTitle(R.string.calculation_dialog_remove_text)
//      .setPositiveButton(R.string.calculation_dialog_button_ok, new DialogInterface.OnClickListener() {
//          public void onClick(DialogInterface dialog, int whichButton) {
//              handleRemoveConfirm(dialogRemove);
//          }
//      })
//      .setNegativeButton(R.string.calculation_dialog_button_cancel, null)
//      .create();
//  }
//  
//  protected void handleRemoveConfirm(int dialogType) {
//      if(dialogType == DIALOG_REMOVE_PERSON){
//          //calc.removePerson();
//      }else if(dialogType == DIALOG_REMOVE_CALC){
//          //removeCalc();
//      }
//  }
//  
////    OnClickListener removeCalcButtonClickListener = new OnClickListener() {
////        public void onClick(View v) {
////            showDialog(DIALOG_REMOVE_CALC);
////        }
////    };
//  
//  @Override
//  protected Dialog onCreateDialog(int id) {
//      switch (id) {
//      case DIALOG_REMOVE_CALC:
//          return createDialogRemoveConfirm(DIALOG_REMOVE_CALC);
//      case DIALOG_REMOVE_PERSON:
//          return createDialogRemoveConfirm(DIALOG_REMOVE_PERSON);
//      }
//      return null;
//  }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

     private void prepareDataList(){
            commentList = new ArrayList<CommentObject>();       
        }   


    // get the selected dropdown list value
      public void addListenerOnButton() {

        spin_prodotto = (Spinner) findViewById(R.id.spin_prodotto);
        spin_tipo = (Spinner) findViewById(R.id.spin_tipo);
        btnAggiungi = (Button) findViewById(R.id.btn_aggiungi);
        btnView_order = (Button) findViewById(R.id.btn_view_order);
        btnNew_order = (Button) findViewById(R.id.btn_new_order);
        EtQta = (EditText) findViewById(R.id.Et_qta);
        //tvOrder = (TextView) findViewById(R.id.tv_ordine);

        btnAggiungi.setEnabled(false);
        btnView_order.setEnabled(false);

        btnNew_order.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                btnAggiungi.setEnabled(true);
                Date now = new Date();
                Order = "Ordine del:\n" +
                        String.valueOf(now.toString())+"\n";

                CommentObject comment = new CommentObject();
                comment.senderName = Order;
                comment.commentText = "Aggiugere i prodotti...";        
                commentList.add(comment);
                adapter.notifyDataSetChanged();
            }

        });

        btnAggiungi.setOnClickListener(new OnClickListener() { 
          @Override
          public void onClick(View v) {

            try {           
                CommentObject comment = new CommentObject();
                comment.senderName = String.valueOf(spin_prodotto.getSelectedItem());
                comment.commentText = "Qtà: "+ String.valueOf(EtQta.getText())+" "+String.valueOf(spin_tipo.getSelectedItem());         
                commentList.add(comment);
                adapter.notifyDataSetChanged();

            } catch (Exception e) {


            }
          }

        });
      }
}

this is my MainActivity.java 这是我的MainActivity.java

package com.bandweb.ordinefornitore.adapter;

import java.util.ArrayList;
import java.util.List;

import com.bandweb.ordinefornitore.R;
import com.bandweb.ordinefornitore.R.id;
import com.bandweb.ordinefornitore.R.layout;
import com.bandweb.ordinefornitore.datastructure.CommentObject;


import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


public class CommentArrayAdapter extends ArrayAdapter<CommentObject>{
    private Context m_context = null;
    private ArrayList<CommentObject> m_comments = null;
    private LayoutInflater m_inflater = null;

    public CommentArrayAdapter(Context context, int textViewResourceId,
            List<CommentObject> objects) {
        super(context, textViewResourceId, objects);

        m_context = context;
        m_comments = (ArrayList<CommentObject>)objects;
        m_inflater = LayoutInflater.from(m_context);
    }

    @Override
    public int getCount() {
        if( m_comments != null ){
            return m_comments.size();
        }
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        CommentViewHolder holder = null;

        //form the view
        if( convertView == null ){
            holder = new CommentViewHolder();
            convertView = m_inflater.inflate(R.layout.order_list_row, parent, false);
            //holder.senderImage = (ImageView)convertView.findViewById(R.id.imgUserImage);
            holder.senderName = (TextView)convertView.findViewById(R.id.txtUserName);
            holder.commentText = (TextView)convertView.findViewById(R.id.txtUserComment);
            holder.removeProductButton = (ImageButton)convertView.findViewById(R.id.remove_product);
            //holder.link = (TextView)convertView.findViewById(R.id.txtClickableLink);

            convertView.setTag(holder);

        }else{

            holder = (CommentViewHolder)convertView.getTag();
        }

        //bind the data to the view
        CommentObject comment = m_comments.get(position);
        holder.senderName.setText(comment.senderName);
        holder.commentText.setText(comment.commentText);
        //final ImageButton clickableText = comment.removeProductButton;
        //holder.link.setOnClickListener(new OnClickListener() {
//          
//          @Override
//          public void onClick(View v) {
//              int duration = Toast.LENGTH_SHORT;
//              Toast toast = Toast.makeText(m_context, clickableText, duration);
//              toast.show();               
//          }
//      });
//      holder.removeProductButton.setOnClickListener(new OnClickListener() {
//          public void onClick(View v) {
//              int duration = Toast.LENGTH_SHORT;
//              Toast toast = Toast.makeText(m_context, "rimuovere", duration);
//              toast.show();   
//
//          }
//      });

        return convertView;
    }

    private class CommentViewHolder{
        ImageButton removeProductButton;
        TextView senderName;
        TextView commentText;
    }
}

this is my CommentArrayAdapter.java 这是我的CommentArrayAdapter.java

package com.bandweb.ordinefornitore.datastructure;

public class CommentObject 
{       
public String senderName;   
public String commentText; 
}

this is my CommentObject.java 这是我的CommentObject.java

package com.bandweb.ordinefornitore;

import android.app.Application;
import android.content.Context;


public class CustomAppContext extends Application {

    private static CustomAppContext context;

    @Override
    public void onCreate() {
        super.onCreate();

        context = this;
    }

    public static CustomAppContext getInstance(){
        return context;
    }

    public static Context getContext(){
        return context.getApplicationContext();
    }

    /*Add your other methods and global variables here*/
}

This is my CustomAppContext.java 这是我的CustomAppContext.java

You can call .remove on your list that populates your view. 您可以在填充视图的列表上调用.remove Afterwards you will want to notifyDataSetChanged to "refresh" the ArrayAdapter 之后,您将需要notifyDataSetChanged“刷新” ArrayAdapter

So if you have an array called mylist that populates your listView 因此,如果您有一个名为mylist的数组来填充listView

mylist.remove(int index):
notifyDataSetChanged();

You can try following : 您可以尝试以下操作:

Replace adapter.remove(itemToRemove); 更换adapter.remove(itemToRemove);

By adapter.remove(adapter.getItem(pos)); 通过adapter.remove(adapter.getItem(pos));

So that your code becomes: 这样您的代码将变为:

protected boolean onLongListItemClick(View v, final int pos, long id) {
                final String str=commentListView.getItemAtPosition(pos).toString();
                Log.i("ListView", "onLongListItemClick stirng=" + str);

                AlertDialog diaBox = AskOption();
                diaBox.show();
                CommentObject itemToRemove = (CommentObject)v.getTag();
                adapter.remove(adapter.getItem(i)); // changed this line
                adapter.notifyDataSetChanged();

                return false;
                }

In your code ArrayList<CommentObject> commentList is collection of CommentObject , hence you must remove that item from your collection using commentList.remove(itemToRemove) and then call adapter.notifyDataSetChanged() , but you are calling remove(itemToRemove) on adapter . 在您的代码ArrayList<CommentObject> commentListCommentObject集合,因此您必须使用commentList.remove(itemToRemove)从集合中删除该项目,然后调用adapter.notifyDataSetChanged() ,但是您要在adapter上调用remove(itemToRemove)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM