我对Android很新,我开始使用RecyclerView
进行练习,但出于某种原因我的数据没有显示。如果你能帮到那就太好了! TY。
这是一些代码。
主要活动:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.myRecyclerView);
adapter = new myAdapter(getApplicationContext(), getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
}
public static List<Information> getData() {
List<Information> data = new ArrayList<>();
String[] titles = { "TEST_TEXT1",
"TEST_TEXT1",
"TEST_TEXT1" };
for (int i = 0; i < titles.length; i++)
Information current = new Information();
current.title = titles[i];
data.add(current);
}
return data;
}
myAdapter:
public class myAdapter extends RecyclerView.Adapter<myAdapter.myViewHolder> {
private LayoutInflater inflater;
List<Information> data = Collections.emptyList();
public myAdapter(Context ctx, List<Information> data) {
inflater = LayoutInflater.from(ctx);
}
@Override
public myViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = inflater.inflate(R.layout.custom_row, viewGroup, false);
myViewHolder holder = new myViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(myViewHolder viewHolder, int i) {
Information current = data.get(i);
viewHolder.user.setText(current.title);
}
@Override
public int getItemCount() {
return data.size();
}
class myViewHolder extends RecyclerView.ViewHolder {
TextView user;
public myViewHolder(View itemView) {
super(itemView);
user = (TextView) itemView.findViewById(R.id.rowUser);
}
}
}
自定义行XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/rowUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="TEST_TEXT"/>
</LinearLayout>
活动布局XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
android:id="@+id/myRecyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
答案 0 :(得分:2)
您不会将列表分配给任何内容。更改构造函数以分配成员变量,如下所示。
public myAdapter(Context ctx, List<Information> data) {
inflater = LayoutInflater.from(ctx);
this.data = data;
}
答案 1 :(得分:0)
这是问题
public myAdapter(Context ctx, List<Information> data) {
inflater = LayoutInflater.from(ctx);
}
你忘记了data
。