安卓 RecyclerView(侧滑删除)

本文介绍如何在Android应用中实现RecyclerView的侧滑删除功能,通过使用SwipeLayout和自定义适配器实现交互效果。同时,深入探讨了断点续传下载的实现,包括指定位置下载、显示进度、分批写入文件等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

RecyclerView(侧滑删除)

SwipeLayout概念:可以支持侧滑的布局控价

常用方法

设置侧滑方式 :setMoe(SwipeLayout.show.PULLOUT)
setMoe(SwipeLayout.show.LAYDOUN)
打开 :openItem(下标)
关闭 :closeItem(下标)
判断是否打开 :isopen(下标)
获得所有已经打开的条目:getopenItem()

注意事项:

1.要写在布局的位置,替换线性或相对布局
2.SwipeLayout嵌套两个子布局,第一个显示在屏幕外,第二个显示内容
3.继承RecyclerSwipeAdapter这个类

效果图

在这里插入图片描述

Java代码

// An highlighted block
package bw.com.swipelayoutapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public class SwipeLayoutMainActivity extends AppCompatActivity {
    RecyclerView recyclerView;
    List<String> list;
    MyAdapter myAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_swipe_layout_main);

        recyclerView = findViewById(R.id.rv);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);

        list = new ArrayList<>();

        for (int i = 1;i<=10;i++){
            list.add("第"+i+"Item");
        }

        myAdapter = new MyAdapter(this,list);
        recyclerView.setAdapter(myAdapter);
        myAdapter.notifyDataSetChanged();

    }
}

适配器代码

// An highlighted block
package bw.com.swipelayoutapplication;

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.Button;
import android.widget.TextView;

import com.daimajia.swipe.SwipeLayout;
import com.daimajia.swipe.adapters.RecyclerSwipeAdapter;

import java.util.List;

public class MyAdapter extends RecyclerSwipeAdapter<MyAdapter.MyViewHolder> {

    private Context context;
    private List<String> list;

    public MyAdapter(Context context, List<String> list) {
        this.context = context;
        this.list = list;
    }

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

    @Override
    public void onBindViewHolder(MyViewHolder viewHolder, final int position) {
        viewHolder.swipeLayout.setShowMode(SwipeLayout.ShowMode.LayDown);
        viewHolder.surface.setText(list.get(position));
        viewHolder.bottom1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                list.remove(position);
                notifyItemRemoved(position);
                notifyItemRangeRemoved(position,list.size());
            }
        });

        viewHolder.bottom2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                list.add(list.get(position));
                notifyDataSetChanged();
                notifyItemRemoved(0);
            }
        });

    }

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

    @Override
    public int getSwipeLayoutResourceId(int position) {
        return position;
    }

    class MyViewHolder extends RecyclerView.ViewHolder{

        private SwipeLayout swipeLayout;
        private Button bottom1;
        private Button bottom2;
        private TextView surface;
        public MyViewHolder(View itemView) {
            super(itemView);
            swipeLayout=itemView.findViewById(R.id.swipe_layout);
            bottom1=itemView.findViewById(R.id.bottom1);
            bottom2=itemView.findViewById(R.id.bottom2);
            surface=itemView.findViewById(R.id.surface);
        }
    }

}

主布局

// An highlighted block
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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=".SwipeLayoutMainActivity">

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

</LinearLayout>

RecyclerView布局

// An highlighted block
<?xml version="1.0" encoding="utf-8"?>
<com.daimajia.swipe.SwipeLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/swipe_layout"
    >

    <LinearLayout
        android:background="#66ddff00"
        android:id="@+id/bottom_wrapper"
        android:layout_width="160dp"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >
        <Button
            android:id="@+id/bottom1"
            android:text="删除"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <Button
            android:id="@+id/bottom2"
            android:text="添加"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>
    <LinearLayout
        android:padding="10dp"
        android:background="#ffffff"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/surface"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="30dp"
            />
    </LinearLayout>

</com.daimajia.swipe.SwipeLayout>

下载文件

效果图

在这里插入图片描述

Java代码

// An highlighted block
package bw.com.breakpointresume;

import android.os.AsyncTask;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.ExecutionException;

/**
 * 指定位置的下载
 *
 * 2.显示下载进度  总长度 当前进度
 *
 * 3.分批写入文件
 * */
public class MainActivity extends AppCompatActivity {
    long start = 0;
    long end  = 1024*1024;//要下载多少
    int max;//给总进度
    Button start_btn;
    Button pare_btn;
    Button button;
    ProgressBar progressBar;
    TextView textView;
    int time = 1;//第几次下载,一共下载5次
    boolean flag = false;
    int sum = 0;
    int num = 0;


    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 100 && msg.obj!= null){
                if (time < num){
                    new LoadFileThread().start();
                    progressBar.setProgress((int) end);
                    time++;
                }else {
                    //不下了发了一个空消息
                    handler.sendEmptyMessage(200);
                    progressBar.setProgress(max);
                }
                textView.setText(msg.obj.toString());
                Log.e("@@@",msg.obj.toString());
            }else if (msg.what == 200){
                textView.setText("下载完成");
            }else if (msg.what == 300){
                progressBar.setProgress(msg.arg1);
            }
        }
    };

    Handler handler2;

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

        start_btn = findViewById(R.id.button_start);
        pare_btn = findViewById(R.id.button_parse);
        button = findViewById(R.id.start_btn);
        progressBar = findViewById(R.id.pb);
        try {
            max = new MyThread().execute("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4").get();
            num = (int) (max/end);
            progressBar.setMax(max);
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        textView = findViewById(R.id.tv);





        start_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new LoadFileThread().start();
            }
        });
        //暂停
        pare_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                flag = true;
                Message message = Message.obtain();
                message.obj = flag;
                handler2.sendMessage(message);
            }
        });

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                flag = false;
                Message message = Message.obtain();
                message.obj = flag;
                handler2.sendMessage(message);
            }
        });



    }

    class MyThread extends AsyncTask<String,String, Integer> {

        @Override
        protected Integer doInBackground(String... strings) {
            try {
                URL url = new URL(strings[0]);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                if (httpURLConnection.getResponseCode() == 200){
                    return httpURLConnection.getContentLength();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }



    class LoadFileThread extends Thread{
        @Override
        public void run() {
            super.run();

            Looper.prepare();//开启

            RandomAccessFile randomAccessFile = null;
            InputStream is = null;
            try {
                URL url = new URL("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4");
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("GET");
                httpURLConnection.setDoInput(true);
                httpURLConnection.setDoOutput(true);


                //存文件的位置
                String path = "";
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
                    path = Environment.getExternalStorageDirectory().getPath()+"/test.mp4";
                }
                randomAccessFile = new RandomAccessFile(path,"rw");
                randomAccessFile.seek(start);

                httpURLConnection.setRequestProperty("Range","bytes="+start+"-"+end);

                if (httpURLConnection.getResponseCode() == 206){
                    Log.e("###","来了老弟");
//                    max = httpURLConnection.getContentLength();//总长度   Range byte = 0-1024*1024
//                    Log.e("MAX",max+"");
//                    progressBar.setMax(max);
                    is = httpURLConnection.getInputStream();
                    byte[] bytes = new byte[1024];
                    int len = 0;
                    while ((len = is.read(bytes))!=-1){
                        randomAccessFile.write(bytes,0,len);
                    }
                    sum+=len;
                }


                //从上次结束的位置+1开始读
                start = end+1;
                end += 1024*1024;


                handler2 = new Handler(){
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                       boolean flag = Boolean.parseBoolean(msg.obj.toString());
                       if (flag){
                           Message message = Message.obtain();
                           message.what = 300;
                           message.arg1 = (int) end;
                           handler.sendMessage(message);
                       }else {
                           Log.e("start",start+"");
                           Log.e("end",end+"");
                           Message message = Message.obtain();
                           message.what = 100;//编号
                           message.obj = "文件第"+time+"次下载成功:"+start+"-"+end;
                           message.arg1 = (int) start;
                           handler.sendMessage(message);
                       }
                    }
                };


                    Log.e("start",start+"");
                    Log.e("end",end+"");
                    Message message = Message.obtain();
                    message.what = 100;//编号
                    message.obj = "文件第"+time+"次下载成功:"+start+"-"+end;
                    message.arg1 = (int) start;
                    handler.sendMessage(message);


            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                if (randomAccessFile != null){
                    try {
                        randomAccessFile.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (is != null){
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            Looper.loop();
        }
    }
}

布局文件

// An highlighted block
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <ProgressBar
        android:id="@+id/pb"
        android:layout_width="match_parent"
        android:layout_height="30dp"
        style="@android:style/Widget.ProgressBar.Horizontal"
        />

    <Button
    android:id="@+id/button_start"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="开始下载"
    />

    <Button
        android:id="@+id/button_parse"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="暂停下载"
        />

    <Button
        android:id="@+id/start_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="继续下载"
        />

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        />
</LinearLayout>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值