如何在我的适配器Android中使用setOnClickListener?

时间:2012-04-17 19:39:18

标签: android

在我的应用程序中,我有ListView和适配器到我的ListView。我的项目ListView有两个元素Text和Image。现在我想分开文本并点击图片。

public class MyAdapter extends ArrayAdapter<String> {
private Activity context;
private ArrayList<String> categories;
public static boolean remove = true;

public MyAdapter(Activity context, ArrayList<String> categories) {
    super(context, R.layout.my_list_element, categories);
    this.context = context;
    this.categories = categories;
}

static class ViewHolder {
    public TextView tvLanguage;
    public ImageView remove;
}

public View getView(int position, View convertView, ViewGroup parent) {
    View rowView = convertView;
    if (rowView == null) {
        LayoutInflater inflater = context.getLayoutInflater();
        rowView = inflater.inflate(R.layout.my_list_element, null);
        ViewHolder viewHolder = new ViewHolder();
        viewHolder.tvLanguage = (TextView) rowView.findViewById(R.id.tvLanguage);
        viewHolder.remove = (ImageView) rowView.findViewById(R.id.remove);
        rowView.setTag(viewHolder);
    }
    ViewHolder holder = (ViewHolder) rowView.getTag();
    holder.tvLanguage.setText(categories.get(position));
    if(remove)
        holder.remove.setVisibility(View.GONE);
    else
        holder.remove.setVisibility(View.VISIBLE);
    return rowView;
}

我应该如何将文本和图像分开并成功在两个元素上使用setOnClickListener?

3 个答案:

答案 0 :(得分:4)

将第一个块修改为:

if (rowView == null) {
        LayoutInflater inflater = context.getLayoutInflater();
        rowView = inflater.inflate(R.layout.my_list_element, null);
        ViewHolder viewHolder = new ViewHolder();
        viewHolder.tvLanguage = (TextView) rowView.findViewById(R.id.tvLanguage);
        viewHolder.remove = (ImageView) rowView.findViewById(R.id.remove);
        rowView.setTag(viewHolder);

        viewHolder.tvLanguage.setOnClickListener(new View.OnClickListener() {
           public void onClick(View v){  
              // handle your text view  
           }
        });

        viewHolder.remove.setOnClickListener(new View.OnClickListener() {
           public void onClick(View v){    
              // handle your imageview
           }
        });

}

答案 1 :(得分:0)

尝试为您的意图添加标记 像这样:

Intent i = new Intent (this, AddRSS.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity (i);

上面的代码将启动活动,并将成为历史堆栈上新任务的开始。

如果这篇文章对您有帮助,请将此帖标记为答案。

感谢。

答案 2 :(得分:0)

我解决了我的问题:)我无法使用此代码

Intent i = new Intent (this, AddRSS.class); 
startActivity (i);

因为我的MyAdapter类没有扩展Activity所以我无法使用方法startActivity(i);

解决方案很简单,我使用上下文:

Intent i = new Intent (context, AddRSS.class); 
context.startActivity (i);

现在有效;)