我正在开发Android 3.1应用程序。
我有ListView
个项目是复选框。 ListView
有一个Button
。
如果选中了一个或多个复选框,我正在尝试启用该按钮。这是我的代码:
public class FormAdapter extends ArrayAdapter<Form>
{
private Context context;
private int layoutResourceId;
private List<Form> forms;
private ArrayList<String> checkedItems;
public ArrayList<String> getCheckedItems()
{
return checkedItems;
}
public FormAdapter(Context context, int textViewResourceId,
List<Form> objects)
{
super(context, textViewResourceId, objects);
this.context = context;
this.layoutResourceId = textViewResourceId;
this.forms = objects;
this.checkedItems = new ArrayList<String>();
}
@Override
public View getView(final int position, final View convertView, ViewGroup parent)
{
View row = convertView;
if (row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
}
Form f = forms.get(position);
if (f != null)
{
CheckBox checkBox = (CheckBox)row.findViewById(R.id.itemCheckBox);
if (checkBox != null)
{
checkBox.setText(f.Name);
checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked)
{
Form f = forms.get(position);
if (isChecked)
{
checkedItems.add(f.FormId);
}
else
{
checkedItems.remove(checkedItems.indexOf(f.FormId));
}
Button dButton = (Button)convertView.findViewById(R.id.downloadFormsButton);
dButton.setEnabled(checkedItems.size() > 0);
}
});
}
}
return row;
}
}
但它不起作用,因为dButton
为NULL。
我已经改变了
public View getView(int position, View convertView, ViewGroup parent)
到这个
public View getView(final int position, final View convertView, ViewGroup parent)
因为eclipse已经建议我了。
我的错误在哪里?
注意:此问题与此Enable a button when user mark a checkbox inside a list item
有关答案 0 :(得分:1)
问题在于这句话:
Button dButton = (Button)convertView.findViewById(R.id.downloadFormsButton);
此处您在列表项视图中调用findViewById
- 但该方法仅查看convertView
下方的视图树。
最好的办法是将此按钮从活动传递到适配器的构造函数中 - 如下所示:
public class FormAdapter extends ArrayAdapter<Form>
{
private Button btnDownload;
........
public FormAdapter(Context context, int textViewResourceId, List<Form> objects, Button btn)
{
........
btnDownload = btn;
........
}
@Override
public View getView(final int position, final View convertView, ViewGroup parent)
{
.......
btnDownload.setEnabled(checkedItems.size() > 0);
.......
}
}
然后在你的活动中:
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
.......
Button btn = (Button)this.findViewById(R.id.downloadFormsButton);
.......
FormAdapter adapter = new FormAdapter(this, textResId, objects, btn);
.......
}