繁体   English   中英

onItem单击gridView适配器项目

[英]onItemClick on gridView adapter item

我有一个使用此自定义适配器的gridView:

package com.example.awesomefilebuilderwidget;

IMPORTS

public class GridViewAdapter extends BaseAdapter {
private Context Context;

// Keep all Images in array list
public ArrayList<Integer> drawables = new ArrayList<Integer>();

CheckBox mCheckBox=null;

// Constructor
public GridViewAdapter(Context c){
    Context = c;
    Log.d("GridViewAdapter", "Constructor is set");

    drawables.add(R.drawable.add_button);
    Log.d("GridViewAdapter", "add_button added");

    drawables.add(R.drawable.pattern1);
    Log.d("GridViewAdapter", "pattern1 added");

    drawables.add(R.drawable.pattern2);
    Log.d("GridViewAdapter", "pattern2 added");

    drawables.add(R.drawable.trashcan);
    Log.d("GridViewAdapter", "trashcan added");

    drawables.add(R.drawable.ic_launcher);
    Log.d("GridViewAdapter", "ic_launcher added");
}

public void setCheckBox(CheckBox checkbox){
    mCheckBox=checkbox;
}

@Override
// How many items are in the data set represented by this Adapter
public int getCount() {
    return drawables.size();
}

@Override
// Get the data item associated with the specified position in the
// data set
public Object getItem(int position) {
    return drawables.get(position);
}

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // Try to reuse the views
    ImageView view = (ImageView) convertView;
    boolean checked = (mCheckBox==null)?false:(((CheckBox)  mCheckBox).isChecked());
    // if convert view is null then create a new instance else reuse it
    if (view == null) {
        view = new ImageView(Context);
        Log.d("GridViewAdapter", "new imageView added");
        view.setId(R.id.iconImageView_id);
    }
    view.setImageResource(drawables.get(position));
    view.setScaleType(ImageView.ScaleType.CENTER_CROP);
    view.setLayoutParams(new android.widget.GridView.LayoutParams(70, 70));
    view.setTag(String.valueOf(position));
    return view;
}

}

我希望能够将onItemClick侦听器设置为在构造函数中创建的图像之一,特别是add_button。 通过环顾四周,我了解到我需要在适配器的getView()方法中执行此操作,但是我不确定如何执行此操作。 我尝试过创建一个单独的add_button ,然后在add_button之外添加add_button图像,但这只引起了我的麻烦,因此我决定在实际的gridView中进行操作。 我怎样才能做到这一点?

我的活动中也有此内容:

android.widget.GridView gridView = (android.widget.GridView) findViewById(R.id.GRIDVIEW1);

    // Instance of Adapter Class
    GridViewAdapter mGridViewAdapter= new GridViewAdapter(this);
    gridView.setAdapter(mGridViewAdapter);
    CheckBox mCheckBox = (CheckBox) findViewById(R.id.addCheckbox);
    mGridViewAdapter.setCheckBox(mCheckBox);

   gridView.setOnItemClickListener(this);

如果我走这条路,我怎么可以设置它,以便OnItemClickListener只做了一定的作用add_button ImageView的?

在OnItemClickListener内,放置if语句以检查单击的项目是否为add_button。 如果是这样,请执行您的操作。

暂无
暂无

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

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