这是我的代码片段。
实际上,我得到的错误是null pointer exception
指向适配器的第一行。
我在其他项目中做了同样的事情,那就是工作得很好。我不知道这是怎么回事?请帮帮我。
public class Tab1 extends Fragment {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
Tab1RecyclerViewAdapter adapter;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab1,container,false);
recyclerView = (RecyclerView) view.findViewById(R.id.tab1RecyclerView);
adapter = new Tab1RecyclerViewAdapter(this.getActivity());
layoutManager = new LinearLayoutManager(this.getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
return view;
}
}
我的适配器
public class Tab1RecyclerViewAdapter extends RecyclerView.Adapter<Tab1RecyclerViewAdapter.RecyclerViewHolder> {
Context context;
Tab1RecyclerViewAdapter(Context ctx) {
context = ctx;
}
@Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.tab1_item,parent,true);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view);
//soundNamePref = context.getSharedPreferences("My_Prefs", Context.MODE_PRIVATE);
//soundPositionPref = context.getSharedPreferences("My_Prefs",Context.MODE_PRIVATE);
return recyclerViewHolder;
}
@Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
}
@Override
public int getItemCount() {
return 2;
}
public class RecyclerViewHolder extends RecyclerView.ViewHolder {
TextView textView;
// CheckBox checkBox;
public RecyclerViewHolder(View itemView)
{
super(itemView);
textView = (TextView) itemView.findViewById(R.id.textView);
}
}
}
我的tab1_item.xml,错误可能是因为其他地方看起来都很好……所以请也看看这个
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:textAlignment="center"
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World"
android:textSize="24dp"
android:textColor="#000"
/>
<view
android:background="#000"
android:layout_below="@+id/textView"
android:layout_width="match_parent"
android:layout_height="2dp"
/>
</RelativeLayout>
这就是我得到的错误。
发布于 2018-08-13 02:00:55
问题是View
的第一个字母必须是大写的view
。它应该看起来像这样
<View
android:background="#000"
android:layout_below="@+id/textView"
android:layout_width="match_parent"
android:layout_height="2dp"
/>
https://stackoverflow.com/questions/51808610
复制相似问题