how to setOnclickListener() on the Button inside the ListView?

Sandroid picture Sandroid · Nov 14, 2011 · Viewed 25.1k times · Source

In app I have a Listactivity which has an adapter with TextView and Button(labeled delete). Now I want to remove corresponding Button clicked item. please check the code and suggest???? `

public class MySimpleArrayAdapter extends ArrayAdapter<String> implements OnClickListener {
    private final Activity context;
    private final String[] names;
    private Button deleteButton= null;
    public MySimpleArrayAdapter(Activity context, String[] names) {
        super (context, R.layout.imagelistlayout, names);
        this.context = context;
        this.names = names;

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = context.getLayoutInflater();
        View rowView = inflater.inflate(R.layout.imagelistlayout, null, true);
        deleteButton= (Button)rowView.findViewById(R.id.delete_bn);
        deleteButton.setTag(position);
        TextView textView = (TextView) rowView.findViewById(R.id.label);
        textView.setText(names[position]);
        deleteButton.setOnClickListener(this); 
        return rowView;

    }

    @Override
    public void onClick(View convertView) {
        System.out.println(deleteButton.getTag());

    }

}` 

I want to know how can I delete the item whose button has been clicked.

Answer

ud_an picture ud_an · Nov 14, 2011

just handle on click listener inside getview where you find the button using findviewbyid

this will handle the current row button click

public class MySimpleArrayAdapter extends ArrayAdapter<String> implements OnClickListener {
    private final Activity context;
    private final String[] names;
    private Button deleteButton= null;
    public MySimpleArrayAdapter(Activity context, String[] names) {
        super (context, R.layout.imagelistlayout, names);
        this.context = context;
        this.names = names;

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = context.getLayoutInflater();
        View rowView = inflater.inflate(R.layout.imagelistlayout, null, true);
        deleteButton= (Button)rowView.findViewById(R.id.delete_bn);
        deleteButton.setTag(position);
        TextView textView = (TextView) rowView.findViewById(R.id.label);
        textView.setText(names[position]);
       deleteButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                //try to hide textview or something it may help
            }
        });
        return rowView;

    }

}`