1

在我的应用程序中,我有 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 ?

4

3 回答 3

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
           }
        });

}
于 2012-04-17T19:43:28.583 回答
0

I solved my problem :) I can't use this code

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

because my class MyAdapter does not extend Activity so I could not use a method startActivity(i);

The solution is simple, I use context :

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

and now works ;)

于 2012-04-18T16:45:13.727 回答
0

尝试像这样向您的意图添加标志:

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

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

于 2012-04-18T02:07:30.067 回答