將多層嵌套 LinearLayout 直接作為列表項佈局,導致 Adapter 難以復用、findViewById 極其繁瑣、性能低下 (黑屏/ANR)。
<!-- item_complex.xml -->
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp">
<TextView android:id="@+id/tvTitle" ... />
<ImageView android:id="@+id/ivIcon" ... />
<TextView android:id="@+id/tvDesc" ... />
<!-- 其他控件扁平排列 -->
</androidx.constraintlayout.widget.ConstraintLayout>
public class ComplexAdapter extends RecyclerView.Adapter {
private List dataList;
static class VH extends RecyclerView.ViewHolder {
TextView tvTitle, tvDesc;
ImageView ivIcon;
VH(View v) {
super(v);
tvTitle = v.findViewById(R.id.tvTitle);
tvDesc = v.findViewById(R.id.tvDesc);
ivIcon = v.findViewById(R.id.ivIcon);
}
}
@NonNull
@Override
public VH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_complex, parent, false);
return new VH(v);
}
@Override
public void onBindViewHolder(@NonNull VH holder, int position) {
DataBean bean = dataList.get(position);
holder.tvTitle.setText(bean.title);
holder.tvDesc.setText(bean.desc);
Glide.with(holder.ivIcon).load(bean.imgUrl).into(holder.ivIcon);
}
@Override
public int getItemCount() { return dataList.size(); }
}
findViewById 僅在創建時執行一次onBindViewHolder 做耗時操作或創建對象getItemViewType + 多 ViewHolder參考教程:Android Adapter 完整指南