Stu Pitt Stu Pitt - 5 months ago 52
Android Question

Android ListView onClickListener Custom Adapter

I read posts about custom adapters and how to index them but it seems i cannot make mine work. I overwrite the getView and my XML contains 1 TextView and 2 Buttons. I made it that both buttons were detected by the onClickListener however i couldnt differentiate which ListView element was the one who triggered the ClickEvent. I tried i different approach but i always get a NullPointerException in the onClick Method.

@Override
public View getView(int position, View convertView, ViewGroup parent){
ViewHolder holder;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.listexample, null);
holder = new ViewHolder();
holder.textView = (TextView) convertView.findViewById(R.id.commandLine_text);
holder.start = (Button) convertView.findViewById(R.id.test_start_button);
holder.stop = (Button) convertView.findViewById(R.id.test_stop_button);
convertView.setTag(holder);
convertView.findViewById(R.id.commandLine_text);
convertView.findViewById(R.id.test_start_button);
convertView.findViewById(R.id.test_stop_button);

} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textView.setText(this.getItem(position));
holder.start.setOnClickListener(this);
holder.stop.setOnClickListener(this);
return convertView;

}
@Override
public void onClick(View v) {
//Here i want to know which button of the two (start,stop) was clicked and what position
int position =(Integer)v.getTag();
Log.d("OnClick","Position: "+position);

}
static class ViewHolder {
TextView textView;
Button start;
Button stop;
}

Answer

Try using getPositionForView(v) to find the position that correlates to the button that was pressed.