我正在尝试在MainActivity上显示我的recyclerView,但似乎无法做到。 这是我的代码:(编译没有错误)
private RecyclerView recyclerView;
private MyAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) this.findViewById(R.id.recycler_view_example);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyAdapter(this, getData());
recyclerView.setAdapter(adapter);
// Add Code to display recyclerView on Main...
}
// This is not my actual data, just testing it out
public static List<Block> getData() {
List<Block> data = new ArrayList<>();
String[] ids = {"310", "313", "320"};
String[] names = {"name of three ten", "name of three thirteen", "name of three twenty"};
for (int i=0; i<ids.length; i++) {
data.add(new Block(ids[i], names[i]));
}
return data;
}
myActivity Class:
private final LayoutInflater inflater;
// Data: (information)
List<Block> data = new ArrayList<>();
public MyAdapter(Context context, List<Block> data) {
inflater = LayoutInflater.from(context);
this.data = data;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.block, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder h, int position) {
MyViewHolder holder = new MyViewHolder(h.itemView);
Block current = data.get(position);
holder.id.setText(current.getId());
holder.name.setText(current.getName());
}
@Override
public int getItemCount() {
return 0;
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView id;
TextView name;
Button button;
// Constructor
public MyViewHolder(View itemView) {
super(itemView);
id = (TextView) itemView.findViewById(R.id.the_course_id);
name = (TextView) itemView.findViewById(R.id.course_name);
button = (Button) itemView.findViewById(R.id.click);
}
}
}
我现在要做的就是当我运行模拟器时,我会看到recyclerView的内容。但是,我一直坚持这一点,因为似乎没有任何效果。 请注意,我是Android的初学者,请原谅我,如果这非常简单。
答案 0 :(得分:1)
您应该在getItemCount
中返回列表中的项目数,如下所示:
@Override
public int getItemCount() {
return data.size();
}
答案 1 :(得分:0)
将onBindViewHolder
更改为:
@Override
public void onBindViewHolder(RecyclerView.ViewHolder h, int position) {
Block current = data.get(position);
h.id.setText(current.getId());
h.name.setText(current.getName());
}
还将@SelçukCihan解决方案添加到此
修改强>
此外,如果您想使用MyViewHolder
,则必须更改以下内容:
首先改变班级签名:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>
并且还更改onBindViewHolder的签名:
public void onBindViewHolder(MyViewHolder h, int position)
最后更改MyViewHolder类的签名:
static class MyViewHolder extends RecyclerView.ViewHolder
答案 2 :(得分:0)
好的,您需要更改以下内容:更新 -
recyclerView.setLayoutManager(new LinearLayoutManager(this));
to
recyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
并在适配器类中更改:
@Override
public int getItemCount() {
return data.size();
}
就是这样。快乐的编码:)