【问题标题】:Deleting item from a Custom ListView从自定义 ListView 中删除项目
【发布时间】:2013-03-29 08:29:54
【问题描述】:

我有一个自定义 ListView,其中填充了从数据库中检索的内容。现在,我无法理解的是如何从列表中删除一个项目:在谷歌上搜索我看到了没有标准解决方案的不同问题,所以我对此表示怀疑。如何使用异步任务从 CustomListView 中删除一行?

这是 Leggi_Pizzaiolo 活动(我在其中显示 listView):

public class Leggi_Pizzaiolo extends Activity
{
    // Progress Dialog
    private ProgressDialog pDialog;
    public List list = new LinkedList();
    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();

    ArrayList<HashMap<String, String>> productsList;

    // url to get all products list
    private static String url_all_products = "http://10.0.2.2/tesina/Leggi_Pizzaiolo.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "Esito";
    private static final String TAG_PRODUCTS = "comande";
    private static final String TAG_PID = "ID";
    private static final String TAG_NAME = "Nome";
    private static final String TAG_TABLE = "Tavolo";
    public ListView lv;
    // products JSONArray
    JSONArray products = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ordini_cuoco);

        // Hashmap for ListView
        productsList = new ArrayList<HashMap<String, String>>();

        // Loading products in Background Thread

        // Get listview
        lv = (ListView)findViewById(R.id.lista);

        new LoadAllProducts().execute();

    }

    /**
     * Background Async Task to Load all product by making HTTP Request
     * */
    class LoadAllProducts extends AsyncTask<String, String, String> 
    {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Leggi_Pizzaiolo.this);
            pDialog.setMessage("Loading products. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting All products from url
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

            // Check your log cat for JSON reponse
            Log.d("All Products: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // products found
                    // Getting Array of Products
                    products = json.getJSONArray(TAG_PRODUCTS);

                    // looping through All Products
                    for (int i = 0; i < products.length(); i++) {
                        JSONObject c = products.getJSONObject(i);

                        // Storing each json item in variable
                        int id = c.getInt(TAG_PID);
                        String name = c.getString(TAG_NAME);
                        int Tavolo= c.getInt(TAG_TABLE);

                        list.add(new Comanda(name, id, Tavolo));

                    }
                } else {
                    // no products found
                    // Launch Add New product Activity
                    Intent i = new Intent(getApplicationContext(),
                            Listino.class);
                    // Closing all previous activities
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) 
        {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating listview
            final ComandaCursorAdapter adapter = new ComandaCursorAdapter(Leggi_Pizzaiolo.this, R.layout.comanda_cuoco, list);
            lv.setAdapter(adapter);


        }



    }


} 

这是 CursorAdapter:

public class ComandaCursorAdapter extends ArrayAdapter<Comanda>
{

public ComandaCursorAdapter(Context context, int comandaCuoco, List list) {
    super(context, comandaCuoco, list);
    // TODO Auto-generated constructor stub
}


@Override
public View getView(int position, View convertView, ViewGroup parent)
{
    LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    convertView = inflater.inflate(R.layout.comanda_cuoco, null);

    TextView Nome = (TextView)convertView.findViewById(R.id.Comanda);
    TextView Tavolo = (TextView)convertView.findViewById(R.id.Tavolo);
    TextView Codice = (TextView)convertView.findViewById(R.id.Codice);

    Comanda c = getItem(position);

    Nome.setText(c.getNome());
    Tavolo.setText("Tavolo: " + Integer.toString(c.getTavolo()));
    Codice.setText("Codice: " + Integer.toString(c.getCodice()));


    return convertView;

}

这是 Comanda 的对象:

public class Comanda {

    private String Nome;
    private int Codice;
    private int Tavolo;

    public Comanda(String Nome, int Codice, int Tavolo)
    {
        this.Nome = Nome;
        this.Codice = Codice;
        this.Tavolo = Tavolo;

    }

    public String getNome()
    {
        return Nome;
    }

    public void setNome(String Nome)
    {
        this.Nome = Nome;
    }

    public int getCodice()
    {
        return Codice;
    }

    public void setCodice(int Codice)
    {
        this.Codice = Codice;
    }

    public int getTavolo()
    {
        return Tavolo;
    }

    public void setTavolo(int Tavolo)
    {
        this.Tavolo = Tavolo;
    }


}

现在,我必须在 Leggi_Pizzaiolo 活动中声明 setOnItemClickListener 吗?我应该在类中实现一个删除方法还是什么?请告诉我如何...

【问题讨论】:

    标签: android android-listview listadapter


    【解决方案1】:

    现在,我不明白如何从列表中删除一个项目

    不,通常创建例如 OnItemClickListener() 以便能够处理 ListView 上的点击事件。然后在 onItemClick() 你有参数 int position 返回适配器中项目的位置。现在您需要从列表中删除项目,然后执行

    list.remove(position)
    

    然后你需要打电话

    adapter.notifyDataSetChanged();
    

    通知适配器数据源已更改。

    注意:为了更加舒适,您可以在单击 ListItem 后显示一些带有删除或不删除按钮的 AlertDialog。

    【讨论】:

    • 又是你! :)) 是的,我也想过 OnItemCliclListener,但我不应该在我的适配器中声明任何删除函数还是只使用 list.remove(position)?
    • @Eulante 不是你说的那样,list.remove(position) 然后调用 notifyDataSetChanged();
    • 我爱你,谢谢!真的真的很有用! :)
    • 昨天我说过,今天下午我会给你发那封著名的邮件!随时回复。再次感谢您!
    【解决方案2】:

    试试这个

     lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> a, View v, int position, long id) {
            AlertDialog.Builder adb=new AlertDialog.Builder(MyActivity.this);
            adb.setTitle("Delete?");
            adb.setMessage("Are you sure you want to delete " + position);
            final int positionToRemove = position;
            adb.setNegativeButton("Cancel", null);
            adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    MyDataObject.remove(positionToRemove);
                    adapter.notifyDataSetChanged();
                }});
            adb.show();
            }
        });
    

    其中 lv 是您的列表视图,adb 是对话框,mydataobject 是您用来填充列表视图的集合,适配器是您的适配器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多