ads_header

Tutorial Swipe To Delete in Android Studio


Tutorial Swipe To Delete in Android Studio



Preview



Halo teman-teman semoga tetap semangat dan bisa menjadi programmer yang handal. Pada postingan kali ini saya ingin berbagi tentang cara membuat program Swipe To Delete di android.

Maksud dari Swipe To Delete adalah penyajian daftar, dimana kita dapat melakukan tindakan terhadap daftar tersebut dengan cara Swipe / Memindahkan satu daftar ke kiri sehingga muncul pilihan tindakan.

Kurang lebih seperti itu penjelasan singkatnya, sekarang buka Android Studio dan buat project baru. kemudian tambahkan beberapa perpustakaan berikut di dependencies

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
    compile "com.daimajia.swipelayout:library:1.2.0@aar"
    compile 'com.android.support:recyclerview-v7:25.1.1'
}

Jika proses Gradle sudah selesai dan tidak ada masalah, maka kita ubah bit warna default dengan cara masuk ke folder values ​​→ colors dan masukkan kode berikut

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#e10404</color>
    <color name="colorPrimaryDark">#b40101</color>
    <color name="colorAccent">@android:color/holo_blue_light</color>  
</resources>

lalu buat layout baru dan beri nama swipe_layout dan masukkan kode berikut

<com.daimajia.swipe.SwipeLayout xmlns:android="http://schemas.android.com/apk/res/android"   
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:id="@+id/swipe"
    app:leftEdgeSwipeOffset="0dp"
    app:rightEdgeSwipeOffset="0dp"
    android:layout_height="wrap_content">

    <LinearLayout
        android:id="@+id/bottom_wraper"
        android:layout_width="240dp"
        android:weightSum="3"
        android:orientation="horizontal"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/Edit"
            android:layout_width="1dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#0076a5"
            android:gravity="center"
            android:text="Edit"
            android:textColor="#fff"/>

        <TextView
            android:id="@+id/Share"
            android:layout_width="1dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#2cbb00"
            android:gravity="center"
            android:text="Share"
            android:textColor="#fff" />

        <TextView
            android:id="@+id/Delete"
            android:layout_width="1dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#ff0000"
            android:gravity="center"
            android:text="Delete"
            android:textColor="#fff"/>

    </LinearLayout>

    <LinearLayout
        android:id="@+id/bottom_wrapper1"
        android:layout_width="80dp"
        android:layout_height="match_parent"
        android:weightSum="1">
        <ImageButton
            android:id="@+id/btnLocation"
            android:layout_width="1dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@null"
            android:gravity="center"
            android:src="@android:drawable/ic_menu_info_details"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?android:selectableItemBackground"
        android:elevation="5dp"
        android:orientation="vertical"
        android:padding="10dp">
        <TextView
            android:id="@+id/Name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:text="Name"
            android:textColor="@android:color/black"
            android:textSize="12sp"/>

        <TextView
            android:id="@+id/EmailId"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:text="Email ID"
            android:textColor="@android:color/black"
            android:textSize="15sp"/>
    </LinearLayout>

</com.daimajia.swipe.SwipeLayout>

Buka activity_main.xml dan masukkan kode berikut

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"   
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/my_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_margin="5dp"
        android:elevation="2dp"
        android:layout_weight="1"
        android:scrollbars="vertical" />
    <TextView
        android:id="@+id/empty_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="No Records"
        android:visibility="gone" />
</LinearLayout>

 CATATAN :

Jadi kami hanya memiliki dua tata letak: activity_main.xml dan swipe_layout.xml





Sekarang buat kelas baru dan beri nama DividetItemDecoration (sesuai keinginan) dan masukkan kode berikut:

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;

public class DividetItemDecoration extends RecyclerView.ItemDecoration {
    private Drawable mDivider;
    private boolean mShowFirstDivider = false;
    private boolean mShowLastDivider = false;

    private DividetItemDecoration(Context context, AttributeSet attrs){
        final TypedArray a = context.obtainStyledAttributes(attrs, new int[android.R.attr.listDivider]);
        mDivider = a.getDrawable(0);
        a.recycle();
    }

    public DividetItemDecoration(Context context, AttributeSet attrs, boolean showFirstDivider,boolean showLastDivider) {   
        this(context, attrs);
        mShowFirstDivider = showFirstDivider;
        mShowLastDivider = showLastDivider;
    }

    public DividetItemDecoration(Drawable divider) {
        mDivider = divider;
    }

    public DividetItemDecoration(Drawable divider, boolean showFirstDivider,boolean showLastDivider) {
        this(divider);
        mShowFirstDivider = showFirstDivider;
        mShowLastDivider = showLastDivider;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);

        if(mDivider == null){
            return;
        }
        if(parent.getChildPosition(view)<1){
            return;
        }

        if(getOrientation(parent)== LinearLayout.VERTICAL){
            outRect.top = mDivider.getIntrinsicHeight();
        }else{
            outRect.top = mDivider.getIntrinsicWidth();
        }
    }

    @Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        if(mDivider==null){
            super.onDrawOver(c, parent, state);
            return;
        }
        int left=0, right=0, top=0, bottom=0, size;
        int orientation = getOrientation(parent);
        int childCount = parent.getChildCount();

        if(orientation == LinearLayoutManager.VERTICAL){
            size = mDivider.getIntrinsicHeight();
            left = parent.getPaddingLeft();
            right = parent.getWidth() - parent.getPaddingRight();
        }
        else{
            size = mDivider.getIntrinsicWidth();
            top = parent.getPaddingTop();
            bottom = parent.getHeight() - parent.getPaddingBottom();
        }

        for (int i = mShowFirstDivider ? 0 : 1; i < childCount; i++) {
            View child = parent.getChildAt(i);
            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();

            if (orientation == LinearLayoutManager.VERTICAL) {
                top = child.getTop() - params.topMargin;
                bottom = top + size;
            } else { //horizontal
                left = child.getLeft() - params.leftMargin;
                right = left + size;
            }
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }

        // divider terakhir
        if (mShowLastDivider && childCount > 0) {
            View child = parent.getChildAt(childCount - 1);
            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
            if (orientation == LinearLayoutManager.VERTICAL) {
                top = child.getBottom() + params.bottomMargin;
                bottom = top + size;
            } else { // horizontal
                left = child.getRight() + params.rightMargin;
                right = left + size;
            }
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }

    private int getOrientation(RecyclerView parent){
        if(parent.getLayoutManager() instanceof LinearLayoutManager){
            LinearLayoutManager layoutManager = (LinearLayoutManager) parent.getLayoutManager();
            return layoutManager.getOrientation();
        }
        else{
            throw new IllegalStateException("bla bla");
        }
    }
}

Selanjutnya buat kelas baru lagi dan beri nama SwipeRecyclerViewAdapter dan masukkan kode berikut:

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.daimajia.swipe.SwipeLayout;
import com.daimajia.swipe.adapters.RecyclerSwipeAdapter;
import java.util.ArrayList;

public class SwipeRecyclerViewAdapter extends RecyclerSwipeAdapter<SwipeRecyclerViewAdapter.SimpleViewHolder> {

    private Context mContext;
    private ArrayList<YoutuberModel> studentList;

    public SwipeRecyclerViewAdapter(Context context, ArrayList<YoutuberModel> objects) {
        this.mContext = context;
        this.studentList = objects;
    }

    @Override
    public SimpleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.swipe_layout, parent, false);
        return new SimpleViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final SimpleViewHolder viewHolder, final int position) {
        final YoutuberModel item = studentList.get(position);

        viewHolder.Name.setText(item.getName() + " - Row Position " + position);
        viewHolder.EmailId.setText(item.getEmailId());
        viewHolder.swipeLayout.setShowMode(SwipeLayout.ShowMode.PullOut);

        //dari kiri
        viewHolder.swipeLayout.addDrag(SwipeLayout.DragEdge.Left, viewHolder.swipeLayout.findViewById(R.id.bottom_wrapper1));   

        //dari kanan
        viewHolder.swipeLayout.addDrag(SwipeLayout.DragEdge.Right, viewHolder.swipeLayout.findViewById(R.id.bottom_wraper));
        viewHolder.swipeLayout.addSwipeListener(new SwipeLayout.SwipeListener() {
            @Override
            public void onStartOpen(SwipeLayout layout) {

            }

            @Override
            public void onOpen(SwipeLayout layout) {

            }

            @Override
            public void onStartClose(SwipeLayout layout) {

            }

            @Override
            public void onClose(SwipeLayout layout) {

            }

            @Override
            public void onUpdate(SwipeLayout layout, int leftOffset, int topOffset) {

            }

            @Override
            public void onHandRelease(SwipeLayout layout, float xvel, float yvel) {

            }
        });

        viewHolder.swipeLayout.getSurfaceView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(mContext, " Click : " + item.getName() + " \n" + item.getEmailId(), Toast.LENGTH_SHORT).show();
            }
        });

        viewHolder.btnLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(v.getContext(), "Clicked on Information " + viewHolder.Name.getText().toString(), Toast.LENGTH_SHORT).show();   
            }
        });

        viewHolder.Share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(view.getContext(), "Clicked on Share " + viewHolder.Name.getText().toString(), Toast.LENGTH_SHORT).show();
            }
        });

        viewHolder.Edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(view.getContext(), "Clicked on Edit  " + viewHolder.Name.getText().toString(), Toast.LENGTH_SHORT).show();
            }
        });

        viewHolder.Delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mItemManger.removeShownLayouts(viewHolder.swipeLayout);
                studentList.remove(position);
                notifyItemRemoved(position);
                notifyItemRangeChanged(position, studentList.size());
                mItemManger.closeAllItems();
                Toast.makeText(v.getContext(), "Deleted " + viewHolder.Name.getText().toString(), Toast.LENGTH_SHORT).show();
            }
        });

        mItemManger.bindView(viewHolder.itemView, position);
    }

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

    @Override
    public int getSwipeLayoutResourceId(int position) {
        return R.id.swipe;
    }

    public static class SimpleViewHolder extends RecyclerView.ViewHolder{
        public SwipeLayout swipeLayout;
        public TextView Name;
        public TextView EmailId;
        public TextView Delete;
        public TextView Edit;
        public TextView Share;
        public ImageButton btnLocation;
        public SimpleViewHolder(View itemView) {
            super(itemView);
            swipeLayout = (SwipeLayout) itemView.findViewById(R.id.swipe);
            Name = (TextView) itemView.findViewById(R.id.Name);
            EmailId = (TextView) itemView.findViewById(R.id.EmailId);
            Delete = (TextView) itemView.findViewById(R.id.Delete);
            Edit = (TextView) itemView.findViewById(R.id.Edit);
            Share = (TextView) itemView.findViewById(R.id.Share);
            btnLocation = (ImageButton) itemView.findViewById(R.id.btnLocation);
        }
    }
}

Mobile Landing Page

Fusion - Mobile App Landing WordPress Theme

Fusion is a WordPress App Landing Page and Portfolio theme delicately handcrafted to meet the needs of a mobile app developers, creative design agency or similar businesses.


Get it Now


Kami masih membutuhkan kelas lagi dan beri nama YoutuberModel dan masukkan kode berikut:

import java.io.Serializable;

public class YoutuberModel implements Serializable {
    private static final long serialVersionUID = 1L;
    private String name;
    private String emailId;
    
    public YoutuberModel(String name, String emailId) {  
        this.name = name;
        this.emailId = emailId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmailId() {
        return emailId;
    }

    public void setEmailId(String emailId) {
        this.emailId = emailId;
    }
}


Dan terakhir buka MainActivity dan masukkan kode berikut

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import com.daimajia.swipe.util.Attributes;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private TextView tvEmptyTextView;
    private RecyclerView mRecyclerView;
    private ArrayList<YoutuberModel> mDataSet;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvEmptyTextView = (TextView) findViewById(R.id.empty_view);
        mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mDataSet = new ArrayList<>();
        
        loadData();
        
        if(mDataSet.isEmpty()){
            mRecyclerView.setVisibility(View.GONE);
            tvEmptyTextView.setVisibility(View.VISIBLE);
        }else{
            mRecyclerView.setVisibility(View.VISIBLE);
            tvEmptyTextView.setVisibility(View.GONE);
        }

        SwipeRecyclerViewAdapter mAdapter = new SwipeRecyclerViewAdapter(this, mDataSet);   

        ((SwipeRecyclerViewAdapter) mAdapter).setMode(Attributes.Mode.Single);

        mRecyclerView.setAdapter(mAdapter);

        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                Log.e("RecyclerView", "onScrollStateChanged");
            }
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
    }
    public void loadData() {
        for (int i = 0; i <= 20; i++) {
            mDataSet.add(new YoutuberModel("Youtuber " + i, "andiaspin" + i + "@gmail.com"));
        }
    }
}

 CATATAN :

Jadi, kita memiliki 4 Kelas: DividetItemDecoration, MainActivity, SwipeRecyclerViewAdapter dan YoutuberModel.
Jika tidak ada kesalahan, maka program siap dijalankan.

Untuk lebih jelasnya silahkan tonton video dibawah ini


No comments:

Powered by Blogger.