public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View itemView = null; if (viewType == 1) { itemView = LayoutInflater.from(MainActivity.this).inflate(R.layout.homeview_list1, parent, false); } else { itemView = LayoutInflater.from(MainActivity.this).inflate(R.layout.homeview_list2, parent, false); } MyViewHolder holder = new MyViewHolder(itemView); return holder; } //将获取的数据设置到对应的控件上 //绑定 @Override public void onBindViewHolder(@NonNull MyViewHolder holder, int position) { holder.onename.setText(titleones[position]); holder.iv.setImageResource(oneicons[position]); holder.twoname.setText(titletwos[position]); holder.lv.setImageResource(twoicons[position]); holder.introduce.setText(introduces[position]); }怎么改
时间: 2024-02-14 07:15:20 浏览: 71
不知道您希望对这段代码进行哪方面的改动,以下是一些可能的改动:
1. 改变 onCreateViewHolder 中的布局加载方式,使用 LayoutInflater 的静态方法 from(parent.getContext()) 更为推荐。
修改后的代码:
```
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = null;
if (viewType == 1) {
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.homeview_list1, parent, false);
} else {
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.homeview_list2, parent, false);
}
MyViewHolder holder = new MyViewHolder(itemView);
return holder;
}
```
2. 在 onBindViewHolder 方法中,对于可能为 null 的数组元素进行判空处理。
修改后的代码:
```
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
if (titleones != null && position < titleones.length) {
holder.onename.setText(titleones[position]);
}
if (oneicons != null && position < oneicons.length) {
holder.iv.setImageResource(oneicons[position]);
}
if (titletwos != null && position < titletwos.length) {
holder.twoname.setText(titletwos[position]);
}
if (twoicons != null && position < twoicons.length) {
holder.lv.setImageResource(twoicons[position]);
}
if (introduces != null && position < introduces.length) {
holder.introduce.setText(introduces[position]);
}
}
```
3. 在 onCreateViewHolder 方法中添加对 viewType 不为 1 或 2 的情况的处理,例如抛出 IllegalArgumentException 异常。
修改后的代码:
```
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = null;
if (viewType == 1) {
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.homeview_list1, parent, false);
} else if (viewType == 2) {
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.homeview_list2, parent, false);
} else {
throw new IllegalArgumentException("viewType must be 1 or 2");
}
MyViewHolder holder = new MyViewHolder(itemView);
return holder;
}
```
阅读全文