【问题标题】:Android studio RecyclerView onCreateViewHolder layout inflation is so slowAndroid studio RecyclerView onCreateViewHolder 布局膨胀好慢
【发布时间】:2020-08-11 20:13:44
【问题描述】:

我有一个根 recyclerview,每个项目都填充了这个布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    >

        <TextView
            android:id="@+id/headerText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/accent_gradient"
            android:ellipsize="end"
            android:maxLines="1"
            android:padding="8dp"
            android:paddingStart="16dp"
            android:text="My original"
            android:textColor="@color/colorWhite"
            android:textSize="14sp" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rootRecycler"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        />
</LinearLayout>

如您所见,每个项目中都有另一个recyclerview。我想用headers实现分段recyclerview的效果。 (所以标题>列表标题>列表)

现在每个 recyclerview 都填充了这个布局视图:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >
        <TextView
            android:layout_toStartOf="@id/relativeLayout3"
            android:layout_marginStart="16dp"
            android:layout_marginEnd="16dp"
            android:id="@+id/foodName_fv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingTop="8dp"
            android:text="Food name"
            android:ellipsize="end"
            android:maxLines="1"
            android:textColor="@color/colorBlack"
            android:textSize="18sp"
            android:transitionName="Food_Name"/>

        <TextView
            android:layout_below="@id/foodName_fv"
            android:layout_marginStart="16dp"
            android:layout_marginEnd="16dp"
            android:id="@+id/foodGrams_fv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingTop="8dp"
            android:paddingBottom="8dp"
            android:text="Grams"
            android:textColor="@color/colorLightGrey"
            android:textSize="15sp" />

    <LinearLayout
        android:id="@+id/relativeLayout3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:orientation="vertical"
        android:layout_alignParentEnd="true"
        >

        <TextView
            android:id="@+id/foodCalories_fv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:text="Calories"
            android:textColor="@color/colorBlack"
            android:textSize="18sp"
            android:transitionName="Food_Cal"/>

        <TextView
            android:layout_gravity="center"
            android:id="@+id/calText_fv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"

            android:paddingBottom="8dp"
            android:text="@string/calText_fv"
            android:textColor="@color/colorLightGrey"
            android:textSize="14sp" />
    </LinearLayout>

</RelativeLayout>

这是一个相当简单的布局,但由于某些奇怪的原因,子 recyclerview 需要花费大量时间来填充这些行。我做了一些测试,加载 300 行(平均)需要 1200 毫秒!

现在最奇怪的是,在这段代码之前,我有一个简单的列表视图(没有任何部分和标题,只是一个大列表),它加载所有这些行的速度非常快。除了这段代码(将它从带有适配器的 listview 转换为带有适配器的 recyclerview)之外,我什么都没有改变,所以它对我来说看起来很奇怪,但我不知道我可能在这里遗漏了一些东西。

这是 onCreateViewHolder 方法:

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.food_view, parent, false);
        return new ViewHolder(view);
    }

总之,子 recyclerview 需要花费太多时间来完成这项工作。是的,我知道我可以进行“延迟加载”,但我想弄清楚为什么它这么慢?

编辑 1: 尝试在一个全新的项目中实现它,以某种方式想到了一些坏事,但它仍然给出了相同的结果,也在我的实际手机而不是模拟器上尝试过,而且仍然很慢。我真的很想弄清楚这个,因为它看起来很不合逻辑。

编辑 2: 发布 hamza khan 的适配器代码:

root recyclerview的代码:

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class SelectFoodRootRecyclerAdapter extends RecyclerView.Adapter<SelectFoodRootRecyclerAdapter.ViewHolder> {

    private static final String TAG = "SelectFoodRootRecyclerAdapter";

    private Context mContext;
    private ArrayList<SectionedFoodGroup> items;
    private ArrayList<SelectFoodChildRecyclerAdapter> adapters; //For filter use outside this class

    RecyclerView.RecycledViewPool recycledViewPool;


    public SelectFoodRootRecyclerAdapter(Context mContext) {
        this.mContext = mContext;

        items = new ArrayList<>();
        adapters = new ArrayList<>();

        recycledViewPool = new RecyclerView.RecycledViewPool();

        SectionedFoodGroup section1 = new SectionedFoodGroup(mContext.getString(R.string.myFoods),
                FoodsDBHelper.getAllFoodRows(Food.DBType.USER_CREATED_FOODS_DB.ordinal()));

        SectionedFoodGroup section2 = new SectionedFoodGroup(mContext.getString(R.string.foods),
                FoodsDBHelper.getAllFoodRows(Food.DBType.REGULAR_FOOD_DB.ordinal()));

        addSection(section1);
        addSection(section2);
    }

    private void addSection(SectionedFoodGroup sectionedFoodGroup){
        if(sectionedFoodGroup.getFoods().size() > 0){
            items.add(sectionedFoodGroup);
            adapters.add(new SelectFoodChildRecyclerAdapter(mContext, sectionedFoodGroup.getFoods()));
        }
    }

    public ArrayList<SelectFoodChildRecyclerAdapter> getAdapters(){
        return adapters;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_sfa_viewholder, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

        SectionedFoodGroup sectionedFoodGroup = items.get(position);

        holder.headerText.setText(sectionedFoodGroup.getHeaderName());

        holder.foodsRecycler.setAdapter(adapters.get(position));
        holder.foodsRecycler.setRecycledViewPool(recycledViewPool);
    }

    @Override
    public int getItemCount() {
        return items != null ? items.size() : 0;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        TextView headerText;
        RecyclerView foodsRecycler;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            headerText = itemView.findViewById(R.id.headerText);
            foodsRecycler = itemView.findViewById(R.id.rootRecycler);
        }
    }
}

子recyclerview的代码(包含所有实际行的那个):

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;

import java.text.DecimalFormat;
import java.util.ArrayList;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class SelectFoodChildRecyclerAdapter extends RecyclerView.Adapter<SelectFoodChildRecyclerAdapter.ViewHolder>{

    private static final String TAG = "SelectFoodChildRecyclerAdapter";

    private Context mContext;

    private ArrayList<Food> original;
    private DecimalFormat decimalFormat;

    public SelectFoodChildRecyclerAdapter(Context mContext, ArrayList<Food> foods) {
        this.mContext = mContext;
        this.original = foods;
        decimalFormat = new DecimalFormat("#.0");
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.food_view, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int foodPos) {
        Food currFood = original.get(foodPos);

        holder.foodName.setText(currFood.getName());

        float grams = 100;
        if(currFood.getAmount() != 0) grams = (float)currFood.getAmount();

        int roundedGrams = (int)Math.round(grams);
        holder.foodGrams.setText(roundedGrams +" "+ mContext.getResources().getString(R.string.gramsWord));

        float caloriesToShow = (float)currFood.getCalories();

        holder.foodCalories.setText(decimalFormat.format(caloriesToShow));
    }

    @Override
    public int getItemCount() {
        return original != null ? original.size() : 0;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView foodName;
        TextView foodGrams;
        TextView foodCalories;

        public ViewHolder(View itemView) {
            super(itemView);
            foodName = itemView.findViewById(R.id.foodName_fv);
            foodGrams = itemView.findViewById(R.id.foodGrams_fv);
            foodCalories = itemView.findViewById(R.id.foodCalories_fv);
        }
    }
}

调用activity的onCreate方法:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_food);

        foodsRecyclerView = findViewById(R.id.rootRecycler);

        selectFoodRootRecyclerAdapter = new SelectFoodRootRecyclerAdapter(this);
        foodsRecyclerView.setAdapter(selectFoodRootRecyclerAdapter);

    }

同样,您可以看到所有代码都相当简单..

编辑 3: 好的,所以我把它缩小了更多。我试着只做第二个布局的一个大回收视图,它运行得很快。 SOOO问题一定出在第一个布局/根recyclerview适配器代码上。但一切似乎都很好......

我真的不知道我在这里错过了什么!感谢您的任何帮助!

谢谢!

【问题讨论】:

  • 也许 RecyclerViewPool 会有所帮助。您可以在多个 recyclerview 之间共享视图。 stackoverflow.com/questions/43332873/…
  • 我刚试了一下,好像没什么用。该死的,这太令人沮丧了!
  • 你能贴出你的适配器的全部代码吗?
  • 您好,当然。生病编辑帖子

标签: android android-layout android-recyclerview


【解决方案1】:

好吧,因为没有人能够回答我的问题,而我已经找到了我的答案,然后我会与其他人分享,他们可能会在未来看到这个并认为,哇,这正是我所需要的。

所以.. 事实证明在 RecyclerView 中使用 RecyclerView 是一个很大的禁忌。那是因为 onCreateViewHolder 方法被调用的次数与您的项目数组大小一样多,而且这非常重,特别是如果您有一个很大的列表。 (我认为它与 ScrollView 中的 RecyclerView 相同) - 所以尽量避免使用这种类型的实现。

那你能做什么?

选项 1 - 创建一个多视图 RecyclerView 适配器。这意味着你有一个适配器,它可以处理多种视图类型(非常适合我想要的。一种视图类型是标题,第二种视图类型是另一种布局,用作我的主行)。

您可以在 google 中查找有关如何实施它的良好结果,但主要 所以声明这些变量:

private int VIEW_TYPE_HEADER = 0;
private int VIEW_TYPE_MAIN_ROW = 1;

Next 覆盖 next 方法,这基本上是为每一行提供一个特殊的 int,然后我们可以在 onCreateViewHolder 中比较它并决定我们要膨胀的布局(例如,如果它是标题或主行)

    @Override
    public int getItemViewType(int itemPos) {
        if(items.get(itemPos) instanceof String){
            return VIEW_TYPE_HEADER;
        }
        return VIEW_TYPE_MAIN_ROW;
    }

在 onCreateViewHolder 上,我们可以测试以查看我们正在处理的行类型并相应地膨胀。

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        if(viewType == VIEW_TYPE_HEADER){
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.header)_layout, parent, false);
            return new HeaderViewHolder(view);
        }
//Else a regular row.
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.main_row, parent, false);
        return new MainViewHolder(view);
    }

当然,为每种类型制作一个单独的视图持有者。

选项 2 - 因为我只需要 2-3 个部分,所以我也可以像这样“硬编码”它:

创建一个 TextView 作为标题,在其下方创建一个 RecyclerView 并再次创建 2-3 次。这种方法显然不太灵活,但如果你想要一些小的,它就可以工作。

希望有一天这会对某人有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-22
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    相关资源
    最近更新 更多