RecyclerView onBindViewHolder导致严重的性能问题

时间:2018-07-30 17:00:25

标签: android android-recyclerview

我有一个TestActivity

public class TestActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        // Setup the Tabs ViewPager
        final SectionsPagerAdapter pagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
        ViewPager pager = (ViewPager) findViewById(R.id.pager);
        // Set the number of tabs to keep in memory
        pager.setOffscreenPageLimit(3);
        pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            int currentPosition = 0;

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int newPosition) {
                FragmentLifecycle fragmentToShow = (FragmentLifecycle)pagerAdapter.getItem(newPosition);
                fragmentToShow.onResumeFragment();

                FragmentLifecycle fragmentToHide = (FragmentLifecycle)pagerAdapter.getItem(currentPosition);
                fragmentToHide.onPauseFragment();

                currentPosition = newPosition;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        pager.setAdapter(pagerAdapter);
        // Attach the ViewPager to the TabLayout
        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(pager);
    }

    private class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }
        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    return new TestFragment();
                case 1:
                    return new TestFragment();
                case 2:
                    return new TestFragment();
                case 3:
                    return new TestFragment();
            }
            return null;
        }

        @Override
        public int getCount() {
            return 4;
        }

        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "Test1";
                case 1:
                    return "Test2";
                case 2:
                    return "Test3";
                case 3:
                    return "Test4";
            }
            return null;
        }
    }
}

通过TestFragment创建4个ViewPager

public class TestFragment extends Fragment implements FragmentLifecycle {

    private RecyclerView testRecycler;
    private ArrayList<TestItem> items;

    public TestFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View layout = inflater.inflate(R.layout.fragment_test, container, false);
        /////////////////// CREATE TEST LIST //
        items = new ArrayList<TestItem>();
        items.add(new TestItem(0, "First1", "Last1"));
        items.add(new TestItem(1, "First2", "Last2"));
        items.add(new TestItem(2, "First3", "Last3"));
        items.add(new TestItem(3, "First4", "Last4"));
        items.add(new TestItem(4, "First5", "Last5"));
        items.add(new TestItem(5, "First6", "Last6"));
        items.add(new TestItem(6, "First7", "Last7"));
        items.add(new TestItem(7, "First8", "Last8"));
        items.add(new TestItem(8, "First9", "Last9"));
        items.add(new TestItem(9, "First10", "Last10"));
        items.add(new TestItem(10, "First11", "Last11"));
        items.add(new TestItem(11, "First12", "Last12"));
        items.add(new TestItem(12, "First13", "Last13"));
        items.add(new TestItem(13, "First14", "Last14"));
        items.add(new TestItem(14, "First15", "Last15"));
        items.add(new TestItem(15, "First16", "Last16"));
        items.add(new TestItem(16, "First17", "Last17"));
        items.add(new TestItem(17, "First18", "Last18"));
        items.add(new TestItem(18, "First19", "Last19"));
        items.add(new TestItem(19, "First20", "Last20"));
        items.add(new TestItem(20, "First21", "Last21"));
        items.add(new TestItem(21, "First22", "Last22"));
        items.add(new TestItem(22, "First23", "Last23"));
        items.add(new TestItem(23, "First24", "Last24"));
        items.add(new TestItem(24, "First25", "Last25"));
        items.add(new TestItem(25, "First26", "Last26"));
        items.add(new TestItem(26, "First27", "Last27"));
        items.add(new TestItem(27, "First28", "Last28"));
        items.add(new TestItem(28, "First29", "Last29"));
        items.add(new TestItem(29, "First30", "Last30"));

        /////////////////// SETUP THE TEST LIST //
        testRecycler = (RecyclerView) layout.findViewById(R.id.test_recycler);
        TestAdapter testAdapter = new TestAdapter(getContext(),
                items);
        testRecycler.setAdapter(testAdapter);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 1);
        testRecycler.setLayoutManager(gridLayoutManager);

        return layout;
    }


    @Override
    public void onPauseFragment() {

    }

    @Override
    public void onResumeFragment() {

    }
}

一切正常,自定义适配器TestAdapter将所有内容对齐:

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

    private Context context;
    private Listener listener;
    private ArrayList<TestItem> items;

    interface Listener {
        void onClick(int position, int id);
    }


    public TestAdapter(Context context, ArrayList<TestItem> items){
        super();
        this.context = context;
        this.items = items;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        private CardView cardView;
        private TextView pupilFullNameTextView;
        private CheckBox absentCheckbox;
        private RadioButton failingButton;
        private RadioButton strugglingButton;
        private RadioButton meetingButton;
        private RadioButton exceedingButton;

        public ViewHolder(CardView view) {
            super(view);
            cardView = view;
            pupilFullNameTextView = view.findViewById(R.id.fullName);
            absentCheckbox = view.findViewById(R.id.absentCheckbox);
            failingButton = view.findViewById(R.id.failing);
            strugglingButton = view.findViewById(R.id.struggling);
            meetingButton = view.findViewById(R.id.meeting);
            exceedingButton = view.findViewById(R.id.exceeding);
        }
    }

    public void setListener(Listener listener) {
        this.listener = listener;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        CardView cv = (CardView) LayoutInflater.from(parent.getContext())
                .inflate(R.layout.card_test, parent, false);
        return new ViewHolder(cv);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        CardView cardView = holder.cardView;
        // Set up the pupils name
        holder.pupilFullNameTextView.setText(items.get(position).getFullName());
    }

    @Override
    public int getItemCount() {
        return items.size();
    }

}

但是绑定过程非常缓慢。加载全部4个片段最多可能需要5秒钟。

我尝试将setAdapter方法移至AsyncTask,因此我可以加载片段然后绑定数据,但是由于UI线程隔离,因此无法正常工作。

但是我不禁以为我做错了事,因为它不应该花那么长时间!

我觉得问题可能出在CardView中使用的RecyclerView的ViewModel中:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/card_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="2dp"
    android:clickable="true"
    android:focusable="true"
    android:foreground="?android:attr/selectableItemBackground"
    card_view:cardCornerRadius="4dp"
    card_view:cardElevation="2dp"
    android:theme="@style/NormalTextAppearance">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/image_view"
            android:layout_width="60dp"
            android:layout_height="60dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.0"
            app:srcCompat="@drawable/ic_default_pic"/>

        <TextView
            android:id="@+id/fullName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:text="TextView"
            app:layout_constraintLeft_toRightOf="@+id/image_view"
            card_view:layout_constraintBottom_toBottomOf="@+id/radioGroup"
            card_view:layout_constraintTop_toTopOf="@+id/radioGroup"/>

        <RadioGroup
            android:id="@+id/radioGroup"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginBottom="8dp"
            android:layout_marginTop="8dp"
            android:orientation="horizontal"
            android:padding="10dp"
            app:layout_constraintBottom_toBottomOf="@+id/image_view"
            app:layout_constraintTop_toTopOf="@+id/image_view"
            card_view:layout_constraintEnd_toEndOf="parent">

            <RadioButton
                android:id="@+id/failing"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginEnd="8dp"
                android:buttonTint="@color/belowExpectations"
                card_view:layout_constraintEnd_toEndOf="parent"
                card_view:layout_constraintTop_toTopOf="parent"/>

            <RadioButton
                android:id="@+id/struggling"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginEnd="8dp"
                android:buttonTint="@color/meetingExpectations"
                card_view:layout_constraintEnd_toStartOf="@+id/belowExpectations"
                card_view:layout_constraintTop_toTopOf="parent"/>

            <RadioButton
                android:id="@+id/meeting"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginEnd="8dp"
                android:buttonTint="@color/exceedingExpectations"
                card_view:layout_constraintEnd_toStartOf="@+id/meetingExpectations"
                card_view:layout_constraintTop_toTopOf="parent"/>

            <RadioButton
                android:id="@+id/exceeding"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginEnd="8dp"
                android:buttonTint="@color/excellingExpectations"
                card_view:layout_constraintEnd_toStartOf="@+id/exceedingExpectations"
                card_view:layout_constraintTop_toTopOf="parent"/>

        </RadioGroup>

        <CheckBox
            android:id="@+id/absentCheckbox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="8dp"
            android:text="Absent"
            app:layout_constraintBottom_toBottomOf="@+id/radioGroup"
            app:layout_constraintEnd_toStartOf="@+id/radioGroup"
            app:layout_constraintTop_toTopOf="@+id/radioGroup"/>


    </android.support.constraint.ConstraintLayout>

</android.support.v7.widget.CardView>

根源太深了吗??

有更好的方法吗?我试图将数据加载到多个CardView条目中,然后通过按下四个RadioButton之一来记录数据:

CardView Entries

正在为此而苦苦挣扎...如果有人可以提出一种推迟数据绑定的方法,而只是先加载片段,那将是最舒适的最坏情况。 FragmentDialog说“正在加载”。如前所述,当我尝试这样做时,我惨败了。

1 个答案:

答案 0 :(得分:1)

findViewById在性能方面非常昂贵。 您应该做的是仅在创建ViewHolder时使用它(在ViewHolders构造函数中),在View中保留对ViewHolder的引用,然后在绑定{{ 1}},例如:

ViewHolder

ViewHolder:

holder.textView.setText("hello")
相关问题