我閱讀關於自定義適配器的帖子,以及如何爲它們編制索引,但似乎我無法讓我的工作。我覆蓋了getView,我的XML包含1個TextView和2個按鈕。我做了兩個按鈕被onClickListener檢測到,但我無法區分哪個ListView元素是觸發ClickEvent的元素。我試過我不同的方法,但我總是在onClick方法中得到一個NullPointerException。Android ListView onClickListener自定義適配器
@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;
}
您需要爲您的按鈕設置標籤'holder.start.setTag(1); holder.start.setTag(2)'然後在'onClick'中獲取標籤 – Raghunandan