LisView je mrtvý, ať žije RecyclerView. Ano, je to opravdu tak, zapomeňte na ListView a začněte používat RecyclerView – je výkonější, flexibilnější a vyvýjí se, ListView je mrtvý.
Pojďme si udělat jednoduchou ukázku.
Do souboru build.gradle je nutné přidat závislost:
dependencies { implementation 'com.android.support:recyclerview-v7:28.0.0' }
1) Přidání RecyclerView do šablony activity_main.xml:
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <android.support.v7.widget.RecyclerView android:id="@+id/my_recycler_view" android:scrollbars="vertical" android:layout_width="match_parent" android:layout_height="match_parent"/> </android.support.constraint.ConstraintLayout>
2) Model
Vytvoříme třídu s Movie.java s gettery a settery.
package cz.vencax.recyclerview.model; public class Movie { private String title, genre, year; public Movie() { } public Movie(String title, String genre, String year) { this.title = title; this.genre = genre; this.year = year; } public String getTitle() { return title; } public void setTitle(String name) { this.title = name; } public String getYear() { return year; } public void setYear(String year) { this.year = year; } public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } }
3) Adapter
Adapter slouží pro zobrazení dat v RecyclerView stejně jako v ListView. Jsou pouze přetížené jiné metody.
Vytvořte třídu s názvem MoviesAdapter.java. Zde metoda onCreateViewHolder () použije movie_list_row.xml. V metodě onBindViewHolder () jsou nastaveny příslušné údaje o filmu (titul, žánr a rok) pro každý řádek.
package cz.vencax.recyclerview.adapter; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.List; import cz.vencax.recyclerview.R; import cz.vencax.recyclerview.model.Movie; public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MyViewHolder> { private List<Movie> moviesList; public class MyViewHolder extends RecyclerView.ViewHolder { public TextView title, year, genre; public MyViewHolder(View view) { super(view); title = (TextView) view.findViewById(R.id.title); genre = (TextView) view.findViewById(R.id.genre); year = (TextView) view.findViewById(R.id.year); } } public MoviesAdapter(List<Movie> moviesList) { this.moviesList = moviesList; } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.movie_list_row, parent, false); return new MyViewHolder(itemView); } @Override public void onBindViewHolder(MyViewHolder holder, int position) { Movie movie = moviesList.get(position); holder.title.setText(movie.getTitle()); holder.genre.setText(movie.getGenre()); holder.year.setText(movie.getYear()); } @Override public int getItemCount() { return moviesList.size(); } }
4) Layout pro řádek v RecyclerView
Vytvořte layout xml s názvem movie_list_row.xml s níže uvedeným kódem. Tento layout vykreslí jeden řádek v RecyclerView se zobrazením názvu filmu, žánru a roku vydání.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="?android:attr/selectableItemBackground" android:clickable="true" android:focusable="true" android:orientation="vertical" android:paddingBottom="10dp" android:paddingLeft="16dp" android:paddingRight="16dp" android:paddingTop="10dp"> <TextView android:id="@+id/title" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:textColor="#222222" android:textSize="16dp" android:textStyle="bold" /> <TextView android:id="@+id/genre" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/title" /> <TextView android:id="@+id/year" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:textColor="#999999" /> </RelativeLayout>
5) Activity
Nakonec upravíme MainActivity.java a provedeme níže uvedené změny. Metoda prepareMovieData () přidá vzorové data do zobrazení v seznamu.
package cz.vencax.recyclerview.activity; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import java.util.ArrayList; import java.util.List; import cz.vencax.recyclerview.R; import cz.vencax.recyclerview.adapter.MoviesAdapter; import cz.vencax.recyclerview.model.Movie; public class MainActivity extends AppCompatActivity { private List<Movie> movieList = new ArrayList<>(); private RecyclerView recyclerView; private MoviesAdapter mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerView = (RecyclerView) findViewById(R.id.recycler_view); mAdapter = new MoviesAdapter(movieList); RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext()); recyclerView.setLayoutManager(mLayoutManager); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setAdapter(mAdapter); prepareMovieData(); } private void prepareMovieData() { Movie movie = new Movie("Mad Max: Fury Road", "Action & Adventure", "2015"); movieList.add(movie); movie = new Movie("Inside Out", "Animation, Kids & Family", "2015"); movieList.add(movie); movie = new Movie("Star Wars: Episode VII - The Force Awakens", "Action", "2015"); movieList.add(movie); movie = new Movie("Shaun the Sheep", "Animation", "2015"); movieList.add(movie); movie = new Movie("The Martian", "Science Fiction & Fantasy", "2015"); movieList.add(movie); movie = new Movie("Mission: Impossible Rogue Nation", "Action", "2015"); movieList.add(movie); movie = new Movie("Up", "Animation", "2009"); movieList.add(movie); movie = new Movie("Star Trek", "Science Fiction", "2009"); movieList.add(movie); movie = new Movie("The LEGO Movie", "Animation", "2014"); movieList.add(movie); movie = new Movie("Iron Man", "Action & Adventure", "2008"); movieList.add(movie); movie = new Movie("Aliens", "Science Fiction", "1986"); movieList.add(movie); movie = new Movie("Chicken Run", "Animation", "2000"); movieList.add(movie); movie = new Movie("Back to the Future", "Science Fiction", "1985"); movieList.add(movie); movie = new Movie("Raiders of the Lost Ark", "Action & Adventure", "1981"); movieList.add(movie); movie = new Movie("Goldfinger", "Action & Adventure", "1965"); movieList.add(movie); movie = new Movie("Guardians of the Galaxy", "Science Fiction & Fantasy", "2014"); movieList.add(movie); mAdapter.notifyDataSetChanged(); } }
A máme hotovo 🙂
6) Přidání oddělovače RecyclerView
recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL)); recyclerView.setAdapter(mAdapter);
7) Přidání click listeneru
RecyclerView také nemá metodu OnItemClickListener pro kliknutí na položku. Musíte napsat svou vlastní třídu implementující RecyclerView.OnItemTouchListener. Vytvořte třídu s názvem RecyclerTouchListener.java:
package cz.vencax.recyclerview.utils; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; public class RecyclerTouchListener implements RecyclerView.OnItemTouchListener { private GestureDetector gestureDetector; private ClickListener clickListener; public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) { this.clickListener = clickListener; gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() { @Override public boolean onSingleTapUp(MotionEvent e) { return true; } @Override public void onLongPress(MotionEvent e) { View child = recyclerView.findChildViewUnder(e.getX(), e.getY()); if (child != null && clickListener != null) { clickListener.onLongClick(child, recyclerView.getChildPosition(child)); } } }); } @Override public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) { View child = rv.findChildViewUnder(e.getX(), e.getY()); if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) { clickListener.onClick(child, rv.getChildPosition(child)); } return false; } @Override public void onTouchEvent(RecyclerView rv, MotionEvent e) { } @Override public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { } public interface ClickListener { void onClick(View view, int position); void onLongClick(View view, int position); } }
Nakonec přidáme tento objekt jako listener k RecyclerView v activity:
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView, new RecyclerTouchListener.ClickListener() { @Override public void onClick(View view, int position) { Movie movie = movieList.get(position); Toast.makeText(getApplicationContext(), movie.getTitle() + " is selected!", Toast.LENGTH_SHORT).show(); } @Override public void onLongClick(View view, int position) { } }));