MASIGNCLEAN101

(Tutorial Android) Grid Layout with GridLayoutManager RecyclerView


Membuat tampilan grid sangat mudah, kita dapat menggunakan GridLayoutManager. GridLayoutManager digunakan untuk menampilkan list yang ada di RecyclerView dalam bentuk grid.

Pada tutorial sebelumnya yaitu (Tutorial Android) RecyclerView and CardView Android Material Design kita menggunakan LinearLayoutManager untuk menampilkan RecyclerView dalam bentuk list.

Nah, sekarang kita akan coba menampilkan RecyclerView dalam bentuk grid.

Import library yang diperlukan


Buat beberapa layout berikut :

Buat layout activity_main.xml


Buat layout fragment_single.xml


Buat layout list_item_single


Setelah semua layoutnya selesai, maka selanjutnya adalah buat kelas-kelas javanya.

Pertama buat kelas pojos dengan nama Single.java *Bukan Jomblo Ya
package wim.example.com.androidgridlayout.model;
/**
* Created by wim on 4/14/16.
*/
public class Single {

private int img;
private String title;

public Single() {
}

public int getImg() {
return img;
}

public void setImg(int img) {
this.img = img;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}
}

Kemudian, buat kelas untuk adapter dengan nama SingleListAdapter.java
package wim.example.com.androidgridlayout.adapter;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import wim.example.com.androidgridlayout.R;
import wim.example.com.androidgridlayout.model.Single;
/**
* Created by wim on 4/14/16.
*/
public class SingleListAdapter extends RecyclerView.Adapter<SingleListAdapter.SingleViewHolder>{

private List<Single> singleList;
private OnGridItemSelectedListener onGridItemSelectedListener;

public SingleListAdapter(OnGridItemSelectedListener onGridItemSelectedListener) {
this.onGridItemSelectedListener = onGridItemSelectedListener;
singleList = new ArrayList<>();
}

private void add(Single item) {
singleList.add(item);
notifyItemInserted(singleList.size() - 1);
}

public void addAll(List<Single> singleList) {
for (Single single : singleList) {
add(single);
}
}

public void remove(Single item) {
int position = singleList.indexOf(item);
if (position > -1) {
singleList.remove(position);
notifyItemRemoved(position);
}
}

public void clear() {
while (getItemCount() > 0) {
remove(getItem(0));
}
}

public Single getItem(int position){
return singleList.get(position);
}

@Override
public SingleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_single, parent, false);
final SingleViewHolder singleViewHolder = new SingleViewHolder(view);
singleViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int adapterPos = singleViewHolder.getAdapterPosition();
if (adapterPos != RecyclerView.NO_POSITION) {
if (onGridItemSelectedListener != null) {
onGridItemSelectedListener.onGridItemClick(singleViewHolder.itemView, adapterPos);
}
}
}
});
return singleViewHolder;
}

@Override
public void onBindViewHolder(SingleViewHolder holder, int position) {
final Single single = singleList.get(position);
holder.img.setImageResource(single.getImg());
holder.title.setText(single.getTitle());
}

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

@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}

@Override
public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
super.onDetachedFromRecyclerView(recyclerView);
}

public class SingleViewHolder extends RecyclerView.ViewHolder {
ImageView img;
TextView title;
public SingleViewHolder(View itemView) {
super(itemView);
img = (ImageView) itemView.findViewById(R.id.img);
title = (TextView) itemView.findViewById(R.id.title);
}
}

public interface OnGridItemSelectedListener {
void onGridItemClick(View v, int position);
}
}

Buat kelas GridMarginDecoration.java. Kelas ini fungsinya memberikan margin disetiap grid item.
package wim.example.com.androidgridlayout.widgets;

import android.content.Context;
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.View;
/**
* Created by wim on 4/14/16.
*/

public class GridMarginDecoration extends RecyclerView.ItemDecoration {

private int left;
private int right;
private int top;
private int bottom;

public GridMarginDecoration(Context context, int left, int right, int top, int bottom) {
this.left = left;
this.right = right;
this.top = top;
this.bottom = bottom;
}

@Override
public void getItemOffsets(
Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
outRect.set(left, top, right, bottom);
}
}

Buat kelas FragmentSingle.java
package wim.example.com.androidgridlayout.fragments;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import wim.example.com.androidgridlayout.R;
import wim.example.com.androidgridlayout.adapter.SingleListAdapter;
import wim.example.com.androidgridlayout.model.Single;
import wim.example.com.androidgridlayout.widgets.GridMarginDecoration;
/**
* Created by wim on 4/14/16.
*/
public class FragmentSingle extends Fragment implements SingleListAdapter.OnGridItemSelectedListener{

private RecyclerView lvSingle;
private GridLayoutManager gridLayoutManager;
private SingleListAdapter singleListAdapter;
private Context context;

public static FragmentSingle newInstance() {
return new FragmentSingle();
}

@Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
}



@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_single, container, false);
lvSingle = (RecyclerView) rootView.findViewById(R.id.lvSingle);
return rootView;
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);

singleListAdapter = new SingleListAdapter(this);
// grid 2 kolom
gridLayoutManager = new GridLayoutManager(context, 2);
lvSingle.setLayoutManager(gridLayoutManager);

// set margin 2 dp
lvSingle.addItemDecoration(new GridMarginDecoration(context, 2, 2, 2, 2));
lvSingle.setAdapter(singleListAdapter);
loadData();
}

private void loadData(){
List<Single> singleList = new ArrayList<>();
Single single;
int img[] = {R.drawable.akb48_43rd_single_kimi_wa_melody, R.drawable.akb48_42nd_single_kuchibiru_ni_be_my_baby,
R.drawable.akb48_41st_single_halloween_night, R.drawable.akb48_40th_single_bokutachi_wa_tatakawanai,
R.drawable.akb48_39th_single_green_flash, R.drawable.akb48_38th_single_kibouteki_refrain,
R.drawable.akb48_37th_single_kokoro_no_placard, R.drawable.akb48_36th_single_labrador_retriever};
String title[] = {"AKB48 43rd Single - Kimi wa Melody", "AKB48 42nd Single - Kuchibiru ni Be My Baby",
"AKB48 41st Single - Halloween Night", "AKB48 40th Single - Bokutachi wa Tatakawanai",
"AKB48 39th Single - Green Flash", "AKB48 38th Single - Kibouteki Refrain",
"AKB48 37th Single - Kokoro no Placard", "AKB48 36th Single - Labrador Retriever"};
for (int i = 0; i < img.length; i++){
single = new Single();
single.setImg(img[i]);
single.setTitle(title[i]);
singleList.add(single);
}
singleListAdapter.addAll(singleList);
}

@Override
public void onGridItemClick(View v, int position) {
Toast.makeText(context, singleListAdapter.getItem(position).getTitle(), Toast.LENGTH_SHORT).show();
}

}

Terakhir buat kelas MainActivity.java
package wim.example.com.androidgridlayout;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import wim.example.com.androidgridlayout.fragments.FragmentSingle;

public class MainActivity extends AppCompatActivity {

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

Fragment fragment = getSupportFragmentManager().findFragmentById(android.R.id.content);
if(fragment == null){
fragment = FragmentSingle.newInstance();
getSupportFragmentManager()
.beginTransaction()
.replace(android.R.id.content, fragment, "")
.commit();
} else {
getSupportFragmentManager()
.beginTransaction()
.attach(fragment)
.commit();
}
}
}

Ok sekarang tinggal build dan jalankan, hasilnya sebagai berikut :



Source lengkap dapat dilihat di https://github.com/wimsonevel/AndroidGridLayout

Sekian dan semoga bermanfaat
Happy Coding :)
Share This :
triana dewi