从适配器中的onclick侦听器获取listiview的对象

时间:2015-08-28 14:00:45

标签: android listview adapter

嗨我有一个listview及其适配器和对象类,每个listview位置都有一个按钮,我在适配器中有一个clicklistener,但当我点击button中的{ {1}}它返回最后一个项目位置。

这是我的适配器:

listview

2 个答案:

答案 0 :(得分:0)

您可以在OnCreate中创建,例如,为列表视图和内部创建方法setOnItemClickListener,询问项目数组中项目的位置。例如,

listview.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
        int pos, long id) {  

        String titulo = array.get(pos).getTitulo();
}

希望有所帮助

再见     });

答案 1 :(得分:0)

好的,我找到了setTag的解决方案:

public class comentario_adapter extends BaseAdapter {
    protected Activity activity;
    protected ArrayList<comentario_obj> items;
    private Context mContext;
    comentario_obj prod;
    ImageButton correcta;
    boolean marcada = false;
    View vi;
    public comentario_adapter(Activity activity, ArrayList<comentario_obj> items, Context context) {
        this.activity = activity;
        this.items = items;
        this.mContext=context;
    }

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

    @Override
    public Object getItem(int position) {
        return items.get(position);
    }

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

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        vi=convertView;

        if(convertView == null) {
            LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            vi = inflater.inflate(R.layout.comentario_adapter, null);
        }

        prod = items.get(position);

        TextView title_coment = (TextView) vi.findViewById(R.id.title_coment);
        ImageButton voteup= (ImageButton) vi.findViewById(R.id.voteup);
        ImageButton votedown= (ImageButton) vi.findViewById(R.id.votedown);
        title_coment.setText(prod.getTitulo());

        final ImageButton btn=(ImageButton)vi.findViewById(R.id.correcta);
        **btn.setTag(prod.getId());**
        btn.setOnClickListener(new Button.OnClickListener() {

            @Override
            public void onClick(View v) {
                if(mContext instanceof verPregunta_class){
                    ((verPregunta_class) mContext).MyMethod();
                        **String title = (String) v.getTag();**
                }
            }
        });

        return vi;
    }
    public interface IMethodCaller{
        void MyMethod();
    }
}

感谢所有人!