gpt4 book ai didi

java - 在 MainActivity 上显示 recyclerView

转载 作者:行者123 更新时间:2023-12-01 09:58:44 25 4
gpt4 key购买 nike

我试图在 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 类:

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 初学者,所以如果这很微不足道,请原谅我。

最佳答案

您应该在 getItemCount 内返回列表中的项目数,如下所示:

@Override
public int getItemCount() {
return data.size();
}

关于java - 在 MainActivity 上显示 recyclerView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36977655/

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