Programing

뷰 홀더가있는 Android Recyclerview 및 ListView

lottogame 2020. 6. 19. 19:24
반응형

뷰 홀더가있는 Android Recyclerview 및 ListView


나는 최근 RecycleView에 안드로이드 5.0과 함께 출시 된 안드로이드 를 발견했으며 ViewHolder 패턴이 통합 RecycleView된 캡슐화 된 전통적인 것으로 보이며 ListView매번 생성하는 대신보기의 재사용을 촉진합니다.

사용의 다른 장점은 무엇입니까 RecycleView? 둘 다 성능면에서 동일한 효과가 있다면 왜 RecycleView를 사용 하는가?

편집하다

나는 사람들이 비슷한 질문을했고 그 답을 결정적이지 않아서 기록을 유지하기 위해 여기에 추가했습니다.

Recyclerview와 Listview

RecyclerView를 사용하여 ListView를 바꿔야합니까?

왜 RecyclerView에 onItemClickListener ()가 없습니까? 그리고 RecyclerView는 Listview와 어떻게 다른가요?


Android Lollipop이 등장하면서 RecyclerView 가 공식적으로 나왔습니다 . RecyclerView는 훨씬 강력하고 유연하며 ListView보다 크게 향상되었습니다 . 이에 대한 자세한 통찰력을 제공 할 것입니다.

1) ViewHolder 패턴

ListView에서는 ViewHolder 패턴을 사용하는 것이 좋지만 절대 강제로 사용하지는 않았습니다. RecyclerView의 경우 RecyclerView.ViewHolder 클래스를 사용해야합니다 . 이것은 ListView와 RecyclerView의 주요 차이점 중 하나입니다.

RecyclerView에서 일을 좀 더 복잡하게 만들지 만 ListView에서 직면 한 많은 문제가 효율적으로 해결됩니다.

2) LayoutManager

이것은 RecyclerView에 또 다른 큰 향상입니다. ListView에서 사용 가능한 유일한보기 유형은 세로 ListView입니다. 수평 ListView를 구현하는 공식적인 방법은 없습니다.

이제 RecyclerView를 사용하여

i) LinearLayoutManager- 세로 및 가로 목록을 모두 지원합니다.

ii) StaggeredLayoutManager-스 태거리스트처럼 Pinterest를 지원합니다.

iii) GridLayoutManager- 갤러리 앱에서 볼 수있는 그리드 표시를 지원합니다.

가장 좋은 점은 원하는대로이 모든 것을 동적으로 수행 할 수 있다는 것입니다.

3) 아이템 애니메이터

ListViews는 우수한 애니메이션을 지원하지 않지만 RecyclerView는 완전히 새로운 차원을 가져옵니다. RecyclerView.ItemAnimator 클래스를 사용하면 뷰 애니메이션이 훨씬 쉽고 직관적입니다.

4) 아이템 장식

ListView의 경우 테두리 또는 구분선 추가와 같은 항목을 동적으로 장식하는 것은 결코 쉬운 일이 아닙니다. 그러나 RecyclerView의 경우 RecyclerView.ItemDecorator 클래스는 개발자에게 강력한 제어 기능을 제공하지만 시간이 많이 걸리고 복잡합니다.

5) OnItemTouchListener

AdapterView.OnItemClickListener 인터페이스 덕분에 ListView에서 항목 클릭을 가로채는 것이 간단했습니다 . 그러나 RecyclerView은에 의해 자사의 개발자들에게 훨씬 더 많은 전력 및 제어 할 수 RecyclerView.OnItemTouchListener 하지만 개발자 일을 조금 복잡하게한다.

간단히 말해서, RecyclerView는 ListView보다 훨씬 사용자 정의가 가능하며 개발자에게 많은 제어 기능과 강력한 기능을 제공합니다.


사용의 또 다른 장점 RecycleView은 애니메이션이며 두 줄의 코드로 수행 할 수 있습니다

RecyclerView.ItemAnimator itemAnimator = new DefaultItemAnimator();
        recyclerView.setItemAnimator(itemAnimator);

그러나 위젯은 여전히 ​​원시적입니다. 예를 들어 headerfooter를 만들 수 없습니다 .


약간 파고 들었고 빌 필립스 기사 에서이 보석을 찾았 습니다.RecycleView

RecyclerView는 ListView 이상을 수행 할 수 있지만 RecyclerView 클래스 자체는 ListView보다 책임이 적습니다. 기본적으로 RecyclerView는 다음을 수행하지 않습니다.

  • 화면에 항목 배치
  • 애니메이션 뷰
  • 스크롤 이외의 모든 터치 이벤트 처리

이 모든 것들이 ListView에 구워졌지만 RecyclerView는 공동 작업 클래스를 사용하여 대신 이러한 작업을 수행합니다.

생성 한 ViewHolders도 더 강력합니다. 그것들 RecyclerView.ViewHolder은 많은 메소드를 RecyclerView사용 하는 서브 클래스 입니다. ViewHolders현재 바인딩 된 위치와 항목 ID (있는 경우)를 알고 있어야합니다. 그 과정에서 ViewHolder기사단이되었습니다. 예전에는 전체 항목보기를 유지하기 위해 ListView의 작업이었고 ViewHolder작은 부분 만 유지했습니다.

이제 ViewHolder는 ViewHolder.itemViewViewHolder의 생성자에 지정된 필드의 모든 항목을 보유 합니다.


Bill Phillip의 기사 에서 더 많은 내용을 읽으십시오 (읽어보십시오!).하지만 다음을 지적하는 것이 중요하다고 생각했습니다.

ListView에는 클릭 이벤트를 처리하는 방법에 대한 모호성이있었습니다. 개별 뷰가 해당 이벤트를 처리해야합니까, 아니면 ListView가 OnItemClickListener를 통해 처리해야합니까? 그러나 RecyclerView에서 ViewHolder는 이러한 종류의 세부 정보를 처리하는 행 수준 컨트롤러 개체로 작동하기에 분명한 위치에 있습니다.

우리는 LayoutManager가 포지셔닝 뷰를 처리하고 ItemAnimator가 애니메이트를 처리하는 것을 앞에서 보았습니다. ViewHolder는 마지막 부분입니다. RecyclerView가 표시하는 특정 항목에서 발생하는 모든 이벤트를 처리합니다.


I used a ListView with Glide image loader, having memory growth. Then I replaced the ListView with a RecyclerView. It is not only more difficult in coding, but also leads to a more memory usage than a ListView. At least, in my project.

In another activity I used a complex list with EditText's. In some of them an input method may vary, also a TextWatcher can be applied. If I used a ViewHolder, how could I replace a TextWatcher during scrolling? So, I used a ListView without a ViewHolder, and it works.


Reuses cells while scrolling up/down - this is possible with implementing View Holder in the listView adapter, but it was an optional thing, while in the RecycleView it's the default way of writing adapter.

Decouples list from its container - so you can put list items easily at run time in the different containers (linearLayout, gridLayout) with setting LayoutManager.

Example:

mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
//or
mRecyclerView.setLayoutManager(new GridLayoutManager(this, 2));
mRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
  • Animates common list actions.

  • Animations are decoupled and delegated to ItemAnimator.

There is more about RecyclerView, but I think these points are the main ones.

LayoutManager

i) LinearLayoutManager - which supports both vertical and horizontal lists,

ii) StaggeredLayoutManager - which supports Pinterest like staggered lists,

iii) GridLayoutManager - which supports displaying grids as seen in Gallery apps.

And the best thing is that we can do all these dynamically as we want.


1. View Holders

In ListView, defining view holders was a suggested approach for keeping references for views. But it was not a compulsion. Although by not doing so, ListView used show stale data. Another major drawback of not using view holders could lead to a heavy operation of finding views by ids every time. Which resulted in laggy ListViews.

This problem is solved in RecylerView by the use of RecyclerView.ViewHolder class. This is one of the major differences in RecyclerView and ListView. When implementing a RecyclerView this class is used to define a ViewHolder object which is used by the adapter to bind ViewHolder with a position. Another point to be noted here, is that while implementing the adapter for RecyclerView, providing a ViewHolder is compulsory. This makes the implementation a little complex, but solves the issues faced in ListView.

2. Layout Manager

When speaking of ListViews, only one type of ListView is available i.e. the vertical ListView. You cannot implement a ListView with horizontal scroll. I know there are ways to implement a horizontal scroll, but believe me it was not designed to work that way.

But now when we look at Android RecyclerView vs ListView, we have support for horizontal collections as well. In-fact it supports multiple types of lists. To support multiple types of lists it uses RecyclerView.LayoutManager class. This is something new that ListView does not have. RecyclerView supports three types of predefined Layout Managers:

LinearLayoutManager – This is the most commonly used layout manager in case of RecyclerView. Through this, we can create both horizontal and vertical scroll lists. StaggeredGridLayoutManager – Through this layout manager, we can create staggered lists. Just like the Pinterest screen. GridLayoutManager– This layout manager can be used to display grids, like any picture gallery.

3. Item Animator

Animations in a list is a whole new dimension, which has endless possibilities. In a ListView, as such there are no special provisions through which one can animate, addition or deletion of items. Instead later on as android evolved ViewPropertyAnimator was suggested by Google’s Chet Haase in this video tutorial for animations in ListView.

On the other hand comparing Android RecyclerView vs ListView, it has RecyclerView.ItemAnimator class for handling animations. Through this class custom animations can be defined for item addition, deletion and move events. Also it provides a DefaultItemAnimator, in case you don’t need any customizations.

4. Adapter

ListView adapters were simple to implement. They had a main method getView where all the magic used to happen. Where the views were bound to a position. Also they used to have an interesting method registerDataSetObserver where one can set an observer right in the adapter. This feature is also present in RecyclerView, but RecyclerView.AdapterDataObserver class is used for it. But the point in favor of ListView is that it supports three default implementations of adapters:

ArrayAdapter CursorAdapter SimpleCursorAdapter Whereas RecyclerView adapter, has all the functionality that ListView adapters had except the built in support for DB cursors and ArrayLists. In RecyclerView.Adapter as of now we have to make a custom implementation to supply data to the adapter. Just like a BaseAdapter does for ListViews. Although if you wish to know more about RecyclerView adapter implementation, please refer to Android RecyclerView Example.

5. Notifying Change in Data

When working with a ListView, if the data set is changed you have to call the notifyDataSetChanged method of the underlying adapter to refresh data. Or set the setNotifyOnChange method to true incase you wish to call the notifyDataSetChanged method automatically. But in both cases the out come is very heavy on the list. Basically it refreshes the views of list.

But on the contrary in a RecyclerView adapter, if a single item or a range of items have changed, there are methods to notify the change accordingly. Those are notifyItemChanged and notifyItemRangeChanged respectively and many more like:

notifyItemInsterted notifyItemMoved notifyItemRangeInsterted notifyItemRangeRemoved And of course it has the original method to refresh the whole list i.e. notifyDataSetChanged which notifies the adapted the whole data set has changed.

6. Item Decoration

To display custom dividers in a ListView, one could have easily added these parameters in the ListView XML:

XHTML android:divider="@android:color/transparent" android:dividerHeight="5dp" 1 2 android:divider="@android:color/transparent" android:dividerHeight="5dp" The interesting part about Android RecyclerView is that, as of now it does not show a divider between items by default. Although the guys at Google must have left this out for customization, intentionally. But this greatly increases the effort for a developer. If you wish to add a divider between items, you may need to do a custom implementation by using RecyclerView.ItemDecoration class.

Or you can apply a hack by using this file from official samples: DividerItemDecoration.java

7. OnItemTouchListener

Listviews used to have a simple implementation for detection of clicks, i.e. by the use of AdapterView.OnItemClickListener interface.

But on the other hand RecyclerView.OnItemTouchListener interface is used to detect touch events in Android RecyclerView. It complicates the implementation a little, but it gives a greater control to the developer for intercepting touch events. The official documentation states, it can be useful for gestural manipulations as it intercepts a touch event before it is delivered to RecyclerView.


RecyclerView was created as a ListView improvement, so yes, you can create an attached list with ListView control, but using RecyclerView is easier as it:

  1. Reuses cells while scrolling up/down : this is possible with implementing View Holder in the ListView adapter, but it was an optional thing, while in the RecycleView it's the default way of writing adapter.

  2. Decouples list from its container : so you can put list items easily at run time in the different containers (linearLayout, gridLayout) with setting LayoutManager.

mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view); mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); mRecyclerView.setLayoutManager(new GridLayoutManager(this, 2));

  1. Animates common list actions : Animations are decoupled and delegated to ItemAnimator. There is more about RecyclerView, but I think these points are the main ones.

So, to conclude, RecyclerView is a more flexible control for handling "list data" that follows patterns of delegation of concerns and leaves for itself only one task - recycling items.

참고URL : https://stackoverflow.com/questions/28525112/android-recyclerview-vs-listview-with-viewholder

반응형