如何在适配器中捕获按钮onClick事件

时间:2016-04-14 22:05:21

标签: android-adapter baseadapter

我有一个带有图像和复选框的网格视图,我还有一个按钮用于删除所选图像。但我无法弄清楚我怎么能抓住onlick事件。我在行中看到了很多关于按钮的例子,但是在列表或网格之外找不到。

我的布局

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFFFFF"
    android:orientation="vertical" >

    <GridView
        android:id="@+id/ImgGrid"
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="0.97"
        android:columnWidth="90sp"
        android:gravity="center"
        android:horizontalSpacing="10sp"
        android:numColumns="auto_fit"
        android:stretchMode="columnWidth"
        android:verticalSpacing="10sp" />

    <RelativeLayout
        android:id="@+id/rlBookmark"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#ffffff"
        android:layout_gravity="bottom" >

        <Button
            android:id="@+id/btnResGridSil"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:text="Sil"
            android:textColor="#FF0011"
            android:textSize="15sp"
            android:textStyle="normal" />
    </RelativeLayout>
</LinearLayout>

这是我的适配器

public class ImageAdapter extends BaseAdapter {
    Button btnsil;
    private LayoutInflater mInflater;
    private ArrayList<ResimBean> mRbList ;
    Context context;
    private ArrayList<Integer> selectedPic = new ArrayList<Integer>();
    public ImageAdapter(Context ctx, ArrayList<ResimBean> rbList, Activity activity) {
        try {
            mInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            mRbList = rbList;
            this.context = ctx;
        } catch (Exception ex) {
            String can = ex.getMessage();
        }
    }

    public int getCount() {
        return mRbList.size();
    }

    public ResimBean getItem(int position) {
        return mRbList.get(position);
    }

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

    public View getView(final int position, View convertView, final ViewGroup parent) {
        ViewHolder holder;
        try {
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = mInflater.inflate(R.layout.resgrid_item, null);
                holder.imageview = (ImageView) convertView.findViewById(R.id.thumbImage);
                holder.checkbox = (CheckBox) convertView.findViewById(R.id.itemCheckBox);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            String path = mRbList.get(position).getResimPath();
            Uri uri = Uri.parse(path);
            Bitmap res = Global.decodeUri(uri, parent.getContext());
            holder.imageview.setImageBitmap(res);
            holder.imageview.setRotation(90);
            final int pos = position;
            holder.checkbox.setTag(position);
            holder.checkbox.setChecked(selectedPic.contains(mRbList.get(position)));
            holder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    int pos = (Integer) buttonView.getTag();
                    if (!buttonView.isChecked()) {
                        selectedPic.remove(pos);
                    } else if (buttonView.isChecked()) {
                        if (!selectedPic.contains(pos)) {
                            selectedPic.add(pos);
                        }
                    }
                }
            });

            holder.imageview.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {

                        Intent intent = new Intent(parent.getContext(), ResimDetayActivity.class);
                        intent.putExtra("reslist", mRbList);
                        intent.putExtra("position",position);

                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(intent);
                    } catch (Exception ex) {

                    }
                }
            });


        } catch (Exception ex) {
            String err = ex.getMessage();

        }
        return convertView;
    }

    public ArrayList<Integer> getSelectedChecckedImages() {
        return selectedPic;
    }

    public void clearSelectedCheckedImages() {
        selectedPic.clear();
    }


}

class ViewHolder {
    ImageView imageview;
    CheckBox checkbox;
    int id;
}

1 个答案:

答案 0 :(得分:0)

虽然使用了Cursor Adapter和ListView,但我所做的是在xml中设置onClick方法,例如膨胀: -

<TextView
    android:id="@+id/shoppinglist_deletebutton"
    android:layout_width="@dimen/standard_dummy_size"
    android:layout_height="@dimen/standard_subsubsubheading_height"
    android:layout_weight="0.05"
    android:singleLine="true"
    android:text="@string/standarddeletetext"
    android:gravity="center"
    android:textSize="@dimen/standard_subsubsubheading_text_size"
    android:textStyle="bold"
    android:background="@color/colorRequiredLabel"
    android:textColor="@color/colorNormalButtonText"
    android:onClick="sledelete"/>        <TextView
    android:id="@+id/shoppinglist_deletebutton"
    android:layout_width="@dimen/standard_dummy_size"
    android:layout_height="@dimen/standard_subsubsubheading_height"
    android:layout_weight="0.05"
    android:singleLine="true"
    android:text="@string/standarddeletetext"
    android:gravity="center"
    android:textSize="@dimen/standard_subsubsubheading_text_size"
    android:textStyle="bold"
    android:background="@color/colorRequiredLabel"
    android:textColor="@color/colorNormalButtonText"
    android:onClick="sledelete"/>

在适配器中(我在bindView而不是getView中执行此操作)我将标记设置为等于游标偏移量(相当于数组offest / index),例如: -

// Set tags to enable onClick to determine the cursor position of the clicked entry
donebtntv.setTag(Integer.valueOf(pos));

然后我在活动中简单地使用相应的方法,例如: -

public void sledone(View view) {
    // Get tag, which is set in ShoppingListAdapter, as it is the position in the list and
    // therefore the cursor of the respective clicked item.
    Integer tag = (Integer)view.getTag();

    String donebuttontext = ((TextView) view.findViewById(view.getId())).getText().toString();
    // If TextView contains Done as text (as per R.string.standarddonebutton) then item/entry
    // has been purchased so decrement quantity required
    if(donebuttontext.equals(getString(R.string.standarddonebutton))) {
        //Toast.makeText(this,"You clicked Done at Position " + Integer.toString(tag) ,Toast.LENGTH_SHORT).show();
        shoppinglistcsr.moveToPosition(tag);
        long quantity = (shoppinglistcsr.getLong(3) - 1);
        shopperdb.changeShopListEntryQuantity(shoppinglistcsr.getLong(0),(shoppinglistcsr.getLong(3) - 1));
        shopperdb.setProductUsageLatestPurchase(shoppinglistcsr.getLong(17),shoppinglistcsr.getLong(9),1);
        shoppinglistcsr = shopperdb.getShoppingList();
        currentsla.swapCursor(shoppinglistcsr);
    }
    // If Textview contains Restore (as per R.string.standardrestorebutton) then item/entry
    // which has 0 quantity is to be restored ie quantity set to 1
    if(donebuttontext.equals(getString(R.string.standardrestorebutton))) {
        shoppinglistcsr.moveToPosition(tag);
        shopperdb.changeShopListEntryQuantity(shoppinglistcsr.getLong(0),1);
        shoppinglistcsr = shopperdb.getShoppingList();
        currentsla.swapCursor(shoppinglistcsr);
    }
}

我认为但不确定,这会自动处理一些复杂性/更精细的细节,例如后代可聚焦性之前/之后(这可能是您遇到的问题)。