在recyclerView.setAdapter(adapter)中通过NullPointerException实现RecyclerView片段。在QuestionScreen.java中
- 请帮忙。
Fragment- QuestionScreen.java
import android.os.Bundle;
import android.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import static com.example.activist.theactivistchallenge.R.layout.questionscreen;
public class QuestionScreen extends Fragment {
RecyclerView recyclerView;
public QuestionScreen() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootview = inflater.inflate(questionscreen, container, false);
recyclerView = (RecyclerView) rootview.findViewById(R.id.question_recycler_view);
RecyclerAdapter adapter = new RecyclerAdapter(getActivity());
recyclerView.setAdapter(adapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return rootview;
}
}
RecyclerAdapter.java
package com.example.activist.theactivistchallenge;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerViewHolder> {
String [] name={"Androidwarriors","Stackoverflow","Developer Android","AndroidHive",
"Slidenerd","TheNewBoston","Truiton","HmkCode","JavaTpoint","Javapeper"};
Context context;
LayoutInflater inflater;
public RecyclerAdapter(Context context) {
this.context=context;
inflater=LayoutInflater.from(context);
}
@Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v=inflater.inflate(R.layout.questionscreen_list, parent, false);
RecyclerViewHolder viewHolder=new RecyclerViewHolder(v);
return viewHolder;
}
@Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
holder.question_desc.setText(name[position]);
}
@Override
public int getItemCount() {
return name.length;
}
}
答案 0 :(得分:0)
rootview.findViewById(R.id.question_recycler_view)
可能会返回null
。
您确定R.layout.questionscreen
中有ID为R.id.question_recycler_view
的视图吗?我不是。