1

基本上我所拥有的是一个显示 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;
    }
}
4

2 回答 2

1

创建一个单独的 .java 文件作为 CustomListAdapter.java 并将您的适配器代码复制到那里

在 CustomListAdapter 的构造函数中

 LayoutInflater inflater;
 public CustomListAdapter(Context context, int resource,
        int textViewResourceId, String[] array) {
    super(context, resource, textViewResourceId, array);
    list = array;
    inflater = LayoutInlfater.from(context); 
}

getView

View row = inflater.inflate(R.layout.workout_row,parent,null); // inflate custom layout
CheckBox cb = (CheckBox) row.findViewById(R.id.checkbox);
// use the inflated view object to initialize checkbox

另外最好使用 ViewHolder 模式

http://developer.android.com/training/improving-layouts/smooth-scrolling.html

于 2013-10-15T18:38:40.120 回答
0

您的适配器需要在您的MyFragment班级内,目前它在您的班级括号之外

于 2013-10-15T18:27:10.973 回答