基本上我所拥有的是一个显示 ListView 的片段。它目前使用 ArrayAdapter。但是我正在尝试扩展 ArrayAdapter 以制作我自己的自定义适配器。然后,当我更改代码以使用我的新适配器时,出现以下错误:
“无法访问 MyActivity 类型的封闭实例。必须使用 MyActivity 类型的封闭实例来限定分配(例如,xnew A(),其中 x 是 MyActivity 的实例)。”
这是代码:请注意,这都嵌套在 MyActivity 中
public static class MyFragment extends ListFragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public MyFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_fixed_tab, container, false);
// Temporarily get the content from an array
String [] values = new String[] { "Item1", "Item2", "Item3", "Item4" };
/******** This has no error as it is, but if I change it to CustomListAdapter, it shows the error ********/
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(), R.layout.workout_row, R.id.workout_name, values);
setListAdapter(adapter);
return rootView;
}
}
private class CustomListAdapter extends ArrayAdapter<String> {
String[] list;
public CustomListAdapter(Context context, int resource,
int textViewResourceId, String[] array) {
super(context, resource, textViewResourceId, array);
list = array;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = super.getView(position, convertView, parent);
CheckBox cb = (CheckBox) findViewById(R.id.checkbox);
cb.setTag(position);
cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
// TBI
}
}
});
return row;
}
}