3

我查看了互联网,一定是遗漏了一些东西。我的任务似乎很简单,我发现了一些其他类似的帖子,但我还没有让我的工作。以下是我的代码(对不起,我是 java 和 android 的新手,所以如果我做了一些不是最佳实践的事情,我深表歉意。)无论如何我的情况,

我有一个 listView 填充数据库中的几个文本字段,在这些文本框的右侧,我创建了一个删除按钮,并希望在按下相应的删除按钮时删除该记录(行)。我已经成功地为我的按钮创建了一个 OnClickListener,但无法在列表视图中获取该按钮已被单击的位置。

---------------------------------------------------
TextView  TextView    | Delete Button
---------------------------------------------------
TextView  TextView    | Delete Button
---------------------------------------------------

代码:

public class CalcCursorAdapter extends SimpleCursorAdapter implements Filterable{

    private Context mContext;
    private ListView mListView;
    private int mLayout;

    protected static class ViewHolder {
        protected TextView text;
        protected ImageButton button;
        private int position;
      }


    @SuppressWarnings("deprecation")
    public CalcCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) 
    {
        super(context, layout, c, from, to);
        this.mContext = context;
        this.mLayout = layout;

        //mListView = .getListView();

    }   

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        TextView summary = (TextView)view.findViewById(R.id.calctvPrice);
        TextView savings = (TextView)view.findViewById(R.id.calctvSavings);
        summary.setText(cursor.getString(cursor.getColumnIndexOrThrow("qcFinalPrice")));
        savings.setText(cursor.getString(cursor.getColumnIndexOrThrow("qcSavings")));



    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        ViewHolder holder = new ViewHolder();

        LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(R.layout.calc_list_item, parent, false);

        holder.button = (ImageButton) v.findViewById(R.id.qcbtnDelete);
        holder.button.setOnClickListener(deleteButton);

        bindView(v, context, cursor);
        v.setTag(holder);
        return v;

    }

    private OnClickListener deleteButton = new OnClickListener() {
        public void onClick(View v){

            Toast.makeText(mContext.getApplicationContext(), "test", Toast.LENGTH_SHORT).show();
        }
    };

    public long qcItemId(int position) {
        return position;
    }
}

我看过很多例子,很多时候它们看起来是针对数组适配器的,我发现的另一件事是有些人会覆盖 getView 函数,我的印象是你可以不这样做就执行上述任务. 另外,我不希望列表项iteslef是可点击的,只是按钮......看起来这应该是一个简单的问题,但我一直在寻找......如果这在某处被很好地覆盖,我很抱歉,我有只是错过了它,我花了过去 4 个小时在网上搜索试图找到解决方法!

无论如何,任何帮助将不胜感激!

谢谢你。

4

2 回答 2

2

玛拉基书的链接为您指明了正确的方向。只是少了一个小细节。Cursor 有一个 getPosition() 方法,它返回光标在行集中的位置。将该值存储在 ViewHolder 中,一切就绪:

holder.position = c.getPosition();

在您的 OnClickListener 中检索 ViewHolder 及其包含的位置:

ViewHolder holder = (ViewHolder) v.getTag();
int position = holder.position;

该位置可用于检索基础数据:

Object myData = getItem(position);
于 2013-05-20T00:43:34.123 回答
0

对于列表中唯一可单击的按钮,只需在 ListView_row.xml 中设置按钮的android:focusable="false"属性android:focusableInTouchMode="false"

现在,您将能够分离 Button 和 Listview 的单击事件。

此外,调用 getView() 是在其中进行自定义时构建列表视图的最佳实践。查看视频教程。我敢肯定你永远不会忘记你将从本教程中学习。

这就是我从列表视图中删除多个项目的方式,不同之处在于我没有从列表中删除任何项目,而是从数据库中删除与它相关的记录,并且我使用了 imageview,而不是按钮。至少你可以知道如何做到这一点:

public class DeleteData extends Activity {

Cursor cursor;
ListView lv_delete_data;
static ArrayList<Integer> listOfItemsToDelete;
SQLiteDatabase database;
private Category[] categories;
ArrayList<Category> categoryList;
private ArrayAdapter<Category> listAdapter;
ImageView iv_delete;

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

    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    manage_reload_list();

    listOfItemsToDelete = new ArrayList<Integer>();

    iv_delete = (ImageView) findViewById(R.id.imageViewDeleteDataDelete);
    iv_delete.setClickable(true);
    iv_delete.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (listOfItemsToDelete.isEmpty()) {

                Toast.makeText(getBaseContext(), "No items selected.",
                        Toast.LENGTH_SHORT).show();
            }

            else {
                showDialog(
                        "Warning",
                        "Are you sure you want to delete these categories ? This will erase all records attached with it.");
            }
        }
    });

    lv_delete_data = (ListView) findViewById(R.id.listViewDeleteData);
    lv_delete_data.setAdapter(listAdapter);
    lv_delete_data.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub
            ImageView imageView = (ImageView) arg1
                    .findViewById(R.id.imageViewSingleRowDeleteData);
            Category category = (Category) imageView.getTag();

            if (category.getChecked() == false) {
                imageView.setImageResource(R.drawable.set_check);
                listOfItemsToDelete.add(category.getId());
                category.setChecked(true);
            } else {
                imageView.setImageResource(R.drawable.set_basecircle);
                listOfItemsToDelete.remove((Integer) category.getId());
                category.setChecked(false);
            }
        }
    });
}

private void showDialog(final String title, String message) {

    AlertDialog.Builder adb = new Builder(DeleteData.this);
    adb.setTitle(title);
    adb.setMessage(message);
    adb.setIcon(R.drawable.ic_launcher);
    String btn = "Ok";
    if (title.equals("Warning")) {
        btn = "Yes";
        adb.setNegativeButton("No", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
    }

    adb.setPositiveButton(btn, new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface arg0, int arg1) {

            if (title.equals("Warning")) {

                for (int i : listOfItemsToDelete) {

                    // -------first delete from category table-----

                    database.delete("category_fields", "cat_id=?",
                            new String[] { i + "" });

                    // --------now fetch rec_id where cat_id =
                    // i-----------------

                    cursor = database.query("records_data",
                            new String[] { "rec_id" }, "cat_id=?",
                            new String[] { i + "" }, null, null, null);
                    if (cursor.getCount() == 0)
                        cursor.close();
                    else {
                        ArrayList<Integer> al_tmp_rec_id = new ArrayList<Integer>();
                        while (cursor.moveToNext())
                            al_tmp_rec_id.add(cursor.getInt(0));
                        cursor.close();

                        for (int i1 : al_tmp_rec_id) {
                            database.delete("records_fields_data",
                                    "rec_id=?", new String[] { i1 + "" });

                            database.delete("record_tag_relation",
                                    "rec_id=?", new String[] { i1 + "" });
                        }

                        // ---------delete from records_data-------

                        database.delete("records_data", "cat_id=?",
                                new String[] { i + "" });

                        cursor.close();
                    }
                }

                showDialog("Success",
                        "Categories, with their records, deleted successfully.");
            } else {
                database.close();
                listOfItemsToDelete.clear();
                manage_reload_list();
                lv_delete_data.setAdapter(listAdapter);
            }
        }
    });

    AlertDialog ad = adb.create();
    ad.show();
}

protected void manage_reload_list() {

    loadDatabase();

    categoryList = new ArrayList<Category>();

    // ------first fetch all categories name list-------

    cursor = database.query("category", new String[] { "cat_id",
            "cat_description" }, null, null, null, null, null);
    if (cursor.getCount() == 0) {
        Toast.makeText(getBaseContext(), "No categories found.",
                Toast.LENGTH_SHORT).show();
        cursor.close();
    } else {

        while (cursor.moveToNext()) {

            categories = new Category[] { new Category(cursor.getInt(0),
                    cursor.getString(1)) };
            categoryList.addAll(Arrays.asList(categories));
        }
        cursor.close();
    }
    listAdapter = new CategoryArrayAdapter(this, categoryList);
}

static class Category {

    String cat_name = "";
    int cat_id = 0;
    Boolean checked = false;

    Category(int cat_id, String name) {
        this.cat_name = name;
        this.cat_id = cat_id;
    }

    public int getId() {
        return cat_id;
    }

    public String getCatName() {
        return cat_name;
    }

    public Boolean getChecked() {
        return checked;
    }

    public void setChecked(Boolean checked) {
        this.checked = checked;
    }

    public boolean isChecked() {
        return checked;
    }

    public void toggleChecked() {
        checked = !checked;
    }
}

static class CategoryViewHolder {

    ImageView imageViewCheck;
    TextView textViewCategoryName;

    public CategoryViewHolder(ImageView iv_check, TextView tv_category_name) {
        imageViewCheck = iv_check;
        textViewCategoryName = tv_category_name;
    }

    public ImageView getImageViewCheck() {
        return imageViewCheck;
    }

    public TextView getTextViewCategoryName() {
        return textViewCategoryName;
    }
}

static class CategoryArrayAdapter extends ArrayAdapter<Category> {

    LayoutInflater inflater;

    public CategoryArrayAdapter(Context context, List<Category> categoryList) {

        super(context, R.layout.single_row_delete_data,
                R.id.textViewSingleRowDeleteData, categoryList);
        inflater = LayoutInflater.from(context);
    }

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

        Category category = (Category) this.getItem(position);

        final ImageView imageViewCheck;
        final TextView textViewCN;

        if (convertView == null) {

            convertView = inflater.inflate(R.layout.single_row_delete_data,
                    null);

            imageViewCheck = (ImageView) convertView
                    .findViewById(R.id.imageViewSingleRowDeleteData);
            textViewCN = (TextView) convertView
                    .findViewById(R.id.textViewSingleRowDeleteData);

            convertView.setTag(new CategoryViewHolder(imageViewCheck,
                    textViewCN));
        }

        else {

            CategoryViewHolder viewHolder = (CategoryViewHolder) convertView
                    .getTag();
            imageViewCheck = viewHolder.getImageViewCheck();
            textViewCN = viewHolder.getTextViewCategoryName();
        }

        imageViewCheck.setFocusable(false);
        imageViewCheck.setFocusableInTouchMode(false);
        imageViewCheck.setClickable(true);
        imageViewCheck.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                ImageView iv = (ImageView) v;
                Category category = (Category) iv.getTag();

                if (category.getChecked() == false) {
                    imageViewCheck.setImageResource(R.drawable.set_check);
                    listOfItemsToDelete.add(category.getId());
                    category.setChecked(true);
                } else {
                    imageViewCheck
                            .setImageResource(R.drawable.set_basecircle);
                    listOfItemsToDelete.remove((Integer) category.getId());
                    category.setChecked(false);
                }
            }
        });
        imageViewCheck.setTag(category);

        if (category.getChecked() == true)
            imageViewCheck.setImageResource(R.drawable.set_check);
        else
            imageViewCheck.setImageResource(R.drawable.set_basecircle);

        textViewCN.setText(category.getCatName());

        return convertView;
    }
}

private void loadDatabase() {
    database = openOrCreateDatabase("WalletAppDatabase.db",
            SQLiteDatabase.OPEN_READWRITE, null);
}
}
于 2013-05-20T01:07:19.687 回答