How do I add an OnClickListener to a button inside a ListView adapter?

You can do so in the getView() method of your adapter. For that you will need to use a custom adapter (if you are not doing that already). It will be better if you can show the relevant portions of your code.

EDIT:
The dialog will be shown by your activity. So you can create an interface for listening to this button click event.

public interface BtnClickListener {
    public abstract void onBtnClick(int position);
}

Let your custom adapter receive it as input.

private BtnClickListener mClickListener = null;
public PerfilAdapter(Context context, List<PerfilBean> lista, BtnClickListener listener) {
    mContext = context;
    mLayoutInflater = (LayoutInflater) mContext
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    listaPerfiles=lista;
    mClickListener = listener;
}

Now you can simply set the normal onClickListener in getView() as below

Button moneda = (Button) itemView.findViewById(R.id.Moneda);
moneda.setTag(position); //For passing the list item index
moneda.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if(mClickListener != null)
            mClickListener.onBtnClick((Integer) v.getTag());                
    }
});

Let your activity pass the required BtnClickListener as part of adapter creation.

perfiladapter = new PerfilAdapter(getApplicationContext(), lst, new BtnClickListener() {

    @Override
    public void onBtnClick(int position) {
        // TODO Auto-generated method stub
        // Call your function which creates and shows the dialog here
        changeMoneda(position);
    }

});

Assuming that lst.get(position).setPerfil_tipoMoneda(item); changes the text which will be used as button text correctly, you should simply call perfiladapter.notifyDataSetChanged() in the onClick of your dialog (Currently you are creating the adapter again which is not required).

public void onClick(DialogInterface dialog, int item) {
    lst.get(position).setPerfil_tipoMoneda(item);
    perfiladapter.notifyDataSetChanged();
    dialog.dismiss();
}

Hope it will work as you expect it to.

Leave a Comment