public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_tab1, container, false);
recyclerView = view.findViewById(R.id.recyler);
adapter = new tabAdapter(getActivity(),getdata());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}
public List<information> getdata(){
List<information> data = new ArrayList<>();
int[] im = {R.mipmap.ic_launcher,R.mipmap.ic_launcher_round,R.mipmap.ic_launcher_round,R.mipmap.ic_launcher};
String[] ti ={"shubham","prasad","xxxxx","dummydata"};
for(int i=0;i<ti.length && i<im.length;i++){
information info = new information();
info.img=im[i];
info.str=ti[i];
data.add(info);
}
return data;
}
并获得例外 致命异议:主要 处理:com.example.android.abc,PID:3385 java.lang.ArrayIndexOutOfBoundsException:length = 4;索引= 4 在com.example.android.abc.tab1.getdata(tab1.java:104) 在com.example.android.abc.tab1.onCreateView(tab1.java:88)
tabAdapter类 public class tabAdapter扩展了RecyclerView.Adapter {
private LayoutInflater lf;
List<information> data = Collections.emptyList();
public tabAdapter(Context context,List data){
lf=LayoutInflater.from(context);
this.data=data;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = lf.inflate(R.layout.res,parent,false);
MyViewHolder ms = new MyViewHolder(view);
return ms;
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
information info=data.get(position);
holder.tx.setText(info.str);
holder.tm.setImageResource(info.img);
}
@Override
public int getItemCount() {
return data.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView tx;
ImageView tm;
public MyViewHolder(View itemView) {
super(itemView);
tx = itemView.findViewById(R.id.ids);
tm = itemView.findViewById(R.id.imag);
}
}
}
答案 0 :(得分:0)
你必须这样做
for(int i=0;i<ti.length;i++){
information info = new information();
info.setImage(im[i]);
info.setString(ti[i]);
data.add(info);
}
更新了答案。
在您bindview
adapter
的{{1}}中,您需要写下面的内容
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
information info=data.get(position);
holder.tx.setText(info.getString());
holder.tm.setImageResource(info.getImage());
}
您的信息类如下
public class information implements Serializable {
private int img;
private String str;
public int getImg() {
return img;
}
public void setImg(int img) {
this.img = img;
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
}