构造函数不匹配自定义适配器
问题描述:
我想创建我的第一个自定义适配器来为我的android应用程序生成一个列表视图。我从一个API调用得到我的数据,然后对其进行处理并将其存储在一个ArrayList: - 在onpostexecute部分我想如下创建一个列表视图和自定义适配器,以显示我的数据构造函数不匹配自定义适配器
class Person{
String bioguide;
String image;
String lastname;
String firstname;
String district;
String state;
String party;}
public static ArrayList<Person> personData = new ArrayList<Person>();
现在: -
ListView yourListView = (ListView) rootView.findViewById(R.id.state_listView);
ListAdapter customAdapter = new ArrayAdapter<Person>(ByState.this, R.layout.bystate_itemview,personData);
yourListView .setAdapter(customAdapter);
}
}
public class ListAdapter extends ArrayAdapter<Person> {
public ListAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
public ListAdapter(Context context, int resource, ArrayList<Person> items) {
super(context, resource, items);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.bystate_itemview, null);
}
Person p = getItem(position);
if (p != null) {
TextView tt1 = (TextView) v.findViewById(R.id.last_name);
TextView tt2 = (TextView) v.findViewById(R.id.first_name);
if (tt1 != null) {
tt1.setText(p.getLastname());
}
if (tt2 != null) {
tt2.setText(p.getFirstname());
}
}
return v;
}
}
}
我得到了上面的代码,一些互联网教程。事情是我在我使用customadapter首先调用自定义适配器的构造函数的行中出现错误。它说无法解析构造函数。有人可以帮助我理解这一点。我知道我没有为我的案例定义适当的构造函数,请让我知道这些变化。我在一个片段内创建了listview,片段类名是ByState。
答
在第二行替换
ListAdapter customAdapter = new ArrayAdapter<Person>(ByState.this, R.layout.bystate_itemview,personData);
通过
ListAdapter customAdapter = new ListAdapter(ByState.this, R.layout.bystate_itemview, personData);
您可以创建自己的适配器类,但调用非标准ArrayAdapter
使用RecyclerView,更多特色的东西。 http://www.androidhive.info/2016/01/android-working-with-recycler-view/ –