本文介绍了recyclerView.setAdapter不接受ArrayAdapter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图用简单的String数据填充RecyclerView,但是recyclerView.setAdapter(adapter);
给出错误.有什么问题吗?
I am trying to populate RecyclerView with simple String data but recyclerView.setAdapter(adapter);
gives error. What's the problem?
我是recyclerview的新手.
I am new to recyclerview.
RecyclerView recyclerView;
String []data = {"ankush", "kapoor"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.myRecyclerView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
}
推荐答案
您必须为RecyclerView创建一个自定义的Adapter类.这是RecyclerView自定义适配器类的示例:
You have to create a custom Adapter class for a RecyclerView. Here is the example of RecyclerView custom adapter class :
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder>{
private LayoutInflater inflater;
private Context context;
<your string array list>
public CustomAdapter(Context context,<your string arraylist>) {
inflater = LayoutInflater.from(context);
this.context = context;
this.<your string arraylist>=<your string arraylist>;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_layout, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.serial_number.setText(<your string array[position]>);
}
@Override
public int getItemCount() {
return <size of your string array list>;
}
class MyViewHolder extends RecyclerView.ViewHolder
{
TextView serial_number;
public MyViewHolder(View itemView) {
super(itemView);
serial_number = (TextView)itemView.findViewById(R.id.serialNo_CL);
}
}
}
这篇关于recyclerView.setAdapter不接受ArrayAdapter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!