Plán na cvičenie

Konkrétne :
  • Otvorenie Android Studio
  • Prerobenie Listview na RecyclerView

RecyclerView a Adapter

Aplikacia, ktora vam zobrazi texty v RecyclerView za pomoci Adaptera.

Developing Android Apps Lesson 3 - RecyclerView

Ukazka vysledku aplikacie:
Ukazka aplikacie

Navod: Pouzite vedomosti z prednasky alebo/a z kurzu Developing Android Apps Lesson 3 - RecyclerView.

Úloha 1

Otvorenie Android Studio a otvorte projekt s ListView.

Ukazka aplikacie:
Ukazka aplikacie (1.krok)

Úloha 2

Vlozte do aplikacie :

  • Do projektoveho gradle vlozte zavislost na RecyclerView
  • Zamente ListView za RecyclerView
  • Nastavte RecyclerView-u LinearLayout.

Kod na inspiraciu:
RecyclerView

Úloha 3

Vytvorte vlastny Adapter pre RecyclerView, v ramci ktoreho musite vytvorit aj ViewHolder pre jednotlive riadky.

Kod na inspiraciu:
RecyclerView

Ukazka vysledku aplikacie:
Ukazka aplikacie

Navod

V projektovom .gradle scripte doplnit zavislost a synchronizovat.

	implementation 'com.android.support:recyclerview-v7:28.0.0'
	

V layoute fragmentu zmenit listview na recyclerView.

	<android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
	android:layout_height="match_parent"/>
	

Vo Fragmente v java kode trebe upravit kod na nasledovny.

// BEGIN_INCLUDE(initializeRecyclerView)
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);

// LinearLayoutManager is used here, this will layout the elements in a similar fashion
// to the way ListView would layout elements. The RecyclerView.LayoutManager defines how
// elements are laid out.
mLayoutManager = new LinearLayoutManager(getActivity());

mRecyclerView.setLayoutManager(mLayoutManager);

 mAdapter = new CustomAdapter(mDataset);
// Set CustomAdapter as the adapter for RecyclerView.
mRecyclerView.setAdapter(mAdapter);
// END_INCLUDE(initializeRecyclerView)

	

Treba vytvorit vlastny Adapter s ViewHolder-om.

public class CustomAdapter extends RecyclerView.Adapter {
	private String[] mDataSet;
	public CustomAdapter(String[] dataSet) {
			mDataSet = dataSet;
	}
	public static class ViewHolder extends RecyclerView.ViewHolder {
		public final TextView textView;
		public ViewHolder(View v) {
			super(v);
			textView = (TextView) v.findViewById(R.id.textView);
		}
	}
	@Override
		public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
			// Create a new view.
			View v = LayoutInflater.from(viewGroup.getContext())
					.inflate(R.layout.text_row_item, viewGroup, false);
			return new ViewHolder(v);
	}	
	@Override
	public void onBindViewHolder(ViewHolder viewHolder, final int position) {
		Log.d(TAG, "Element " + position + " set.");

		// Get element from your dataset at this position and replace the contents of the view
		// with that element
		viewHolder.textView.setText(mDataSet[position]);
	}
}
	

Odporucane kurzy

  • Developing Android Apps
  • Ukazkovy kod

  • RecyclerView
  •