gpt4 book ai didi

android - 将 ArrayAdapter 更改为扩展 ArrayAdapter 的自定义适配器时出现错误

转载 作者:行者123 更新时间:2023-11-30 03:19:38 27 4
gpt4 key购买 nike

基本上我所拥有的是一个显示 ListView 的 fragment 。它目前使用 ArrayAdapter。但是,我正在尝试扩展 ArrayAdapter 以制作我自己的自定义适配器。然后,当我更改代码以使用我的新适配器时,出现以下错误:

“无法访问 MyActivity 类型的封闭实例。必须使用 MyActivity 类型的封闭实例来限定分配(例如 x.new 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;
}
}

最佳答案

创建一个单独的 .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

关于android - 将 ArrayAdapter<String> 更改为扩展 ArrayAdapter<String> 的自定义适配器时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19388285/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com