ListView项目按钮禁用

时间:2014-06-23 04:03:16

标签: android listview android-listview

我有一个用于listView的自定义baseadapter。现在我在每个listView项目上都有按钮。我需要禁用它们的按钮。但是,当我点击其中一个按钮时,列表上会有多个按钮禁用。我附上了代码。

@Override
public View getView(int arg0, View convertView, ViewGroup arg2) {
    // TODO Auto-generated method stub
    final int k = arg0;
    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.list_view_element, null);

    }
    TextView name = (TextView)convertView.findViewById(R.id.textView1);
    name.setText(arrayList.get(arg0).getName());
    TextView phone = (TextView)convertView.findViewById(R.id.textView2);
    phone.setText(arrayList.get(arg0).getPhoneNum());

    Button request = (Button)convertView.findViewById(R.id.button1);


    request.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Update the local database of Request table
            databaseHelper.insertRequestTable(new Person(arrayList.get(k).getName(), arrayList.get(k).getPhoneNum()));
            ((Button)arg0).setEnabled(false);
        }
    });


    return convertView;
}

请帮忙。

1 个答案:

答案 0 :(得分:-1)

Button request = (Button)convertView.findViewById(R.id.button1);
// this refers to all button in the list view you

// viewholder holds reference of bojects 
public static class ViewHolder {
    TextView name;
    TextView phone;
    Button request;
}

@Override
public View getView(int arg0, View convertView, ViewGroup arg2) {
// TODO Auto-generated method stub
final int k = arg0;
if (convertView == null || convertView.getTag() == null) {
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    convertView = inflater.inflate(R.layout.list_view_element, null);
    holder = new ViewHolder();
    // save the references in the holder 
    holder.name = (TextView)convertView.findViewById(R.id.textView1);
    holder.phone = (TextView)convertView.findViewById(R.id.textView2);
    holder.request = (Button)convertView.findViewById(R.id.button1);
    // save this references to view so the you can get it back to set some thing
    convertView.setTag(holder);
} else {
    // get the reference back 
    holder = (ViewHolder) convertView.getTag();
}

holder.name.setText(arrayList.get(arg0).getName());

holder.phone.setText(arrayList.get(arg0).getPhoneNum());
// this will refer to button you want not all
holder.request.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) {
        // TODO Update the local database of Request table
        databaseHelper.insertRequestTable(new Person(arrayList.get(k).getName(), arrayList.get(k).getPhoneNum()));
        ((Button)arg0).setEnabled(false);
    }
});
return convertView;
}

GitHub项目:https://github.com/rathodvikas10/android-examples/tree/master/ListView