首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android Studio 中複雜 LinearLayout 佈局的 Adapter 正確實現方式

     編輯:程式設計綜合問答

問題核心

將多層嵌套 LinearLayout 直接作為列表項佈局,導致 Adapter 難以復用、findViewById 極其繁瑣、性能低下 (黑屏/ANR)。

正確架構:ViewHolder + 扁平化佈局

1. 佈局優化:ConstraintLayout 替換嵌套 LinearLayout

<!-- 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>

2. Adapter 實現 (RecyclerView 強烈推薦)

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(); }
}

3. 關鍵優勢

  • ViewHolder 緩存:findViewById 僅在創建時執行一次
  • 扁平佈局:渲染層級減少 60%+,滑動流暢
  • 類型安全:泛型 + ViewBinding (可選) 消除強轉
  • 異步圖片加載:Glide/Picasso/Coil 自動處理生命周期、緩存

避坑指南

  1. 不要在 onBindViewHolder 做耗時操作或創建對象
  2. 多類型列表用 getItemViewType + 多 ViewHolder
  3. 若必須用 ListView,同樣要實現 ViewHolder 模式
  4. 佈局預覽工具 (Layout Inspector) 定位過度繪製

參考教程:Android Adapter 完整指南

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved