这个问题可能是因为在AndroidX迁移后,ListView被替换为RecyclerView,需要使用RecyclerView.Adapter代替ListView.Adapter。以下是示例代码:
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.Adapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new MyAdapter();
recyclerView.setAdapter(mAdapter);
}
private class MyAdapter extends RecyclerView.Adapter {
private ArrayList data = new ArrayList<>();
MyAdapter() {
data.add("item 1");
data.add("item 2");
// add more data here
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_layout, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
holder.textView.setText(data.get(position));
}
@Override
public int getItemCount() {
return data.size();
}
}
private static class MyViewHolder extends RecyclerView.ViewHolder {
private TextView textView;
MyViewHolder(@NonNull View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.textView);
}
}
}
在这个示例中,MyAdapter类代替了原来的ListView.Adapter。在MyAdapter类中,我们可以添加数据,实现数据的显示和更新。可通过ViewHodler类保持item视图的引用,而不需要反复调用findViewById()方法。