我阅读了有关自定义适配器以及如何索引它们的帖子,但似乎我无法让我的工作。我覆盖了 getView,我的 XML 包含 1 个 TextView 和 2 个按钮。我做到这两个按钮都被 onClickListener 检测到,但是我无法区分哪个 ListView 元素是触发 ClickEvent 的元素。我尝试了不同的方法,但我总是在 onClick 方法中得到 NullPointerException。
@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;
}