RecyclerView
的 Fragment
无效,其显示错误和应用程序在运行时崩溃。
public class FragmentList extends Fragment {
String [] names={"Nitin","Manish","Ankit","Hardik","Mayur","Mayank"};
RecyclerView mRecyclerView;
Context context;
RecyclerAdapter mAdapter;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.fragment_list,container,false);
setupRecyclerView();
return v;
}
private void setupRecyclerView() {
mRecyclerView= (RecyclerView)getView().findViewById(R.id.recycler_nit);
LinearLayoutManager mLayout= new LinearLayoutManager(context);
mLayout.setOrientation(LinearLayoutManager.VERTICAL);
mAdapter= new RecyclerAdapter(context,names);
mRecyclerView.setAdapter(mAdapter);
}
在运行时显示错误,应用程序在启动前崩溃,
这是RecyclerView
的适配器类:
Context context;
String[] names;
public RecyclerAdapter(Context context, String[] names) {
this.context = context;
this.names = names;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder vh;
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.raw_list,parent,false);
vh=new ViewHolder(v);
return (ViewHolder) vh;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.txt.setText(names[position]);
}
@Override
public int getItemCount() {
return 0;
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView txt;
public ViewHolder(View itemView) {
super(itemView);
txt= (TextView) itemView.findViewById(R.id.name_listtext);
}
}
显示:
致命的例外:主要 处理:com.example.hp.newfragment,PID:3354
java.lang.RuntimeException:无法启动活动 ComponentInfo {com.example.hp.newfragment / com.example.hp.newfragment.MainActivity}: android.view.InflateException:二进制XML文件行#17:错误 膨胀类片段
提前感谢您的帮助......
答案 0 :(得分:3)
你必须设置布局管理器
喜欢这个
private void setupRecyclerView() {
mRecyclerView= (RecyclerView)getView().findViewById(R.id.recycler_nit);
LinearLayoutManager mLayout= new LinearLayoutManager(context);
mRecyclerView.setLayoutManager(mLayout);// here u have to add
mLayout.setOrientation(LinearLayoutManager.VERTICAL);