简体   繁体   中英

How to make a ImageView Clickable in a ListView using SimpleAdapter?

I have a Listview which is generated using a SimpleAdapter. My Listview displays another Listview when I click on a row. I have placed an ImageView in the adapter. I want to make the ImageView clickable to change the picture of the ImageView.Can anyone suggest me how to do it? I am posting my code below:

public View onCreateView(LayoutInflater inflater1, ViewGroup container,
            Bundle savedInstanceState) {

   View rootView = inflater1.inflate(R.layout.listview_header_row, container, false);
   final ImageView im=(ImageView)rootView.findViewById(R.id.imageView1);
   SharedPreferences pref = getActivity().getPreferences(0);
   final String id = pref.getString("mynumber", "empty");
   Databasehandler db=new Databasehandler(getActivity().getApplicationContext());
   final ListView l=(ListView) rootView.findViewById(R.id.listViewad);
   val=db.getTaskSent(id);
   ListAdapter k=new SimpleAdapter(getActivity(),val,R.layout.r,new String[]{"TaskId","heading"},new int[]{R.id.textViews,R.id.textViews1});
   l.setAdapter(k);

   im.setOnClickListener(new OnClickListener() {
      @Override
       public void onClick(View arg0) {
          // TODO Auto-generated method stub
          Toast.makeText(getActivity(), "json", Toast.LENGTH_SHORT).show();
       }
   });

     l.setOnItemClickListener(new OnItemClickListener() {
           @Override
          public void onItemClick(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
              TextView tv2=(TextView) arg1.findViewById(R.id.textViews);
              String t=tv2.getText().toString();
              Intent i4=new Intent(getActivity(),SentTaskOnclick.class);
              i4.putExtra("taskId",t);
              startActivity(i4);
          }
    });

I will share some of my code, and I think you can have an idea to your problem. You can also download and test the code for yourself: https://github.com/lpbaptista/Party-Monsters

This is my cell class where I manage the click and change the image color (I just need to set the picture to be at grayscale in this example)

public class CategoryCell extends RelativeLayout implements OnClickListener{

private Category category;
private ImageView icon;
private boolean selected = true;

public CategoryCell(Context context, AttributeSet attrs) {
    super(context,attrs);
    LayoutInflater.from(getContext()).inflate(R.layout.category_cell, this, true);
    setOnClickListener(this);
}

public void init(Category category){
    this.category = category;
    icon = (ImageView)findViewById(R.id.category_icon);
    icon.setImageDrawable(category.getIcon(getContext()));
    icon.getDrawable().clearColorFilter();
    if(isSelected())
        GlobalState.getInstance().addCategory(category);
}

public CategoryCell(Context context) {
    this(context,null);
}

@Override
public void onClick(View v) {
    setSelected(!isSelected());
}

public boolean isSelected() {
    return selected;
}

public void setSelected(boolean selected) {
    if(category==null)
        return;
    this.selected = selected;
    if(!isSelected()){
        ColorMatrix matrix = new ColorMatrix();
        matrix.setSaturation(0);
        ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
        icon.getDrawable().setColorFilter(filter);
        icon.invalidate();
        GlobalState.getInstance().removeCategory(category);
    }else{
        GlobalState.getInstance().addCategory(category);
        icon.getDrawable().clearColorFilter();
        icon.invalidate();
    }
}

public Category getCategory() {
    return category;
}

}

Here you can look at my Row class where I just add the cells to my view

public class CategoryRow extends LinearLayout {

private LinearLayout root;
private Map<Category,CategoryCell> cells = new HashMap<Category, CategoryCell>();


public CategoryRow(Context context, AttributeSet attrs) {
    super(context, attrs);
    root = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.category_row, this, true);
}

public CategoryRow(Context context) {
    super(context);
    root = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.category_row, this, true);
}

public static CategoryRow create(ViewGroup parent, LayoutInflater inflater) {
    final CategoryRow view = new CategoryRow(parent.getContext());
    return view;
}

public void init(Type type, List<Category> cells) {
    LinearLayout ll = (LinearLayout)root.getChildAt(0);
    for(int i = 0;i<cells.size();i++) {
        CategoryCell cell = ((CategoryCell)ll.getChildAt(i));
        cell.init(cells.get(i));
        this.cells.put(cells.get(i),cell);
    }
}

public Map<Category,CategoryCell> getCells() {
    return cells;
}

}

And finally the List code:

public class CategoryList extends ListView {

private List<List<Category>> categories = new ArrayList<List<Category>>();
private Map<Category,CategoryCell> cells = new HashMap<Category, CategoryCell>();
private Type type;

public CategoryList(Context context, AttributeSet attrs) {
    super(context, attrs);
    setBackgroundColor(getResources().getColor(R.color.wet_asphalt));
    setDivider(null);
    setVerticalFadingEdgeEnabled(false);
    setVerticalScrollBarEnabled(false); 
    setHorizontalScrollBarEnabled(false);
    Utils.changeRoundedCornersColor(this, R.color.carrot,false);
    if(isInEditMode())
        init(Type.BAR);
}

public void init(Type type){
    this.type = type;
    categories.clear();
    if(getAdapter()!=null)
        ((CategoryAdapter)getAdapter()).notifyDataSetChanged();
    setAdapter(null);
    categories = loadCells();
    setAdapter(new CategoryAdapter());
    ((CategoryAdapter)getAdapter()).notifyDataSetChanged();
}

private List<List<Category>> loadCells() {
    List<List<Category>> cells = new ArrayList<List<Category>>();
    int rowLimitCounter = 0;
    ArrayList<Category> categoryCells = null;
    Category[] categories = Category.values();
    for(int i = 0;i<categories.length;i++){
        if(rowLimitCounter==0)
            categoryCells = new ArrayList<Category>();
        categoryCells.add(categories[i]);
        rowLimitCounter++;
        if(rowLimitCounter>3 || i == (categories.length-1)){
            cells.add(categoryCells);
            rowLimitCounter=0;
        }
    }
    return cells;
}

private class CategoryAdapter extends BaseAdapter{

    private final LayoutInflater inflater;

    public CategoryAdapter() {
        inflater = LayoutInflater.from(getContext());
    }

    @Override
    public boolean isEnabled(int position) {
        return false;
    }

    @Override 
    public int getCount() {
        return categories.size();
    }

    @Override 
    public List<Category> getItem(int position) {
        return categories.get(position);
    }

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

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) {
        CategoryRow row = (CategoryRow) convertView;
        if (row == null) {
            row = CategoryRow.create(parent, inflater);
        }
        row.init(type, categories.get(position));
        cells.putAll(row.getCells());
        return row;
    }
}
}

If you have any doubt on this just ask and I will try to help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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