Recycler view занимает 30 секунд для загрузки, а также тормозит при прокрутке - PullRequest
0 голосов
/ 13 октября 2019

Я следовал этому уроку ("https://www.youtube.com/watch?v=Yt15bySZTf0") и создаю список видео, доступных в моем мобильном хранилище и на SD-карте, но когда я запускаю приложение, загрузка первой операции занимает около 30 секунд, чтоэто список всех доступных видео, а также, когда представление рециркулятора доступно, и я начинаю прокрутку, прокрутка идет медленно, пожалуйста, помогите мне решить эту проблему. Ниже приведен код моего приложения

video_list_items.xml

<?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"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" > <!--if you add match parent it will cause large spaces between files while scrolling-->


    <android.support.v7.widget.CardView
        android:id="@+id/videoCardView"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        app:cardElevation="3dp"
        android:layout_gravity="center"
        android:layout_margin="4dp"
        app:cardUseCompatPadding="true">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:weightSum="5">

            <ImageView
                android:id="@+id/VideoImageView"
                android:layout_width="wrap_content"
                android:layout_height="0dp"
                android:layout_weight="4"
                android:scaleType="centerCrop"
                android:layout_gravity="center"/>
            <TextView
                android:id="@+id/VideoTextView"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1"
                android:layout_margin="5dp"
                android:maxLines="1"
                android:text="File Name"/>

        </LinearLayout>

    </android.support.v7.widget.CardView>

</LinearLayout>

VideoAdapter.java

import android.content.Context;
import android.graphics.Bitmap;
import android.media.ThumbnailUtils;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.widget.CardView;
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 com.example.hdvideoandaudioplayer.MainActivity;
import com.example.hdvideoandaudioplayer.R;

import java.io.File;
import java.util.ArrayList;

public class VideoAdapter extends RecyclerView.Adapter<VideoViewHolder> {

    private Context context;
    ArrayList<File> videoArrayList;

    public VideoAdapter(Context context, ArrayList<File> videoArrayList) {
        this.context = context;
        this.videoArrayList = videoArrayList;
    }

    @Override
    public VideoViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {

        View vView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.video_list_items, viewGroup, false);
        return new VideoViewHolder(vView);
    }

    @Override
    public void onBindViewHolder(@NonNull VideoViewHolder videoViewHolder, int i) {
        videoViewHolder.vTextView.setText(MainActivity.fileArrayList.get(i).getName());
        Bitmap bitmapThumbnail = ThumbnailUtils.createVideoThumbnail(videoArrayList.get(i).getPath(), MediaStore.Video.Thumbnails.MINI_KIND);
        videoViewHolder.vImageView.setImageBitmap(bitmapThumbnail);
    }

    @Override
    public int getItemCount() {

        if(videoArrayList.size()>0){
            return videoArrayList.size();
        }
        else {
            return 1;
        }
    }

}

class VideoViewHolder extends RecyclerView.ViewHolder {

    TextView vTextView;
    ImageView vImageView;
    CardView vCardView;

    public VideoViewHolder(@NonNull View itemView) {
        super(itemView);

        vTextView = itemView.findViewById(R.id.VideoTextView);
        vImageView = itemView.findViewById(R.id.VideoImageView);
        vCardView = itemView.findViewById(R.id.videoCardView);
    }
}

activity_main.xml

<?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=".MainActivity">

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

    </android.support.v7.widget.RecyclerView>

</LinearLayout>

MainActivity.java

package com.example.hdvideoandaudioplayer;

import android.Manifest;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;

import com.example.hdvideoandaudioplayer.Adapter.VideoAdapter;

import java.io.File;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    RecyclerView mRecyclerView;
    VideoAdapter obj_VideoAdapter;
    public static int REQUEST_PERMISSION = 1;
    File directory;
    boolean BOOLEAN_PERMISSION;
    public static ArrayList<File> fileArrayList = new ArrayList<>();

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

        mRecyclerView = findViewById(R.id.videoListRecyclerView);
        directory = new File("/mnt/");
        GridLayoutManager gridLayoutManager = new GridLayoutManager(MainActivity.this, 2);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setItemViewCacheSize(20);
        mRecyclerView.setLayoutManager(gridLayoutManager);

        permissionForVideo();
    }

    private void permissionForVideo() {
        if((ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)){

            if((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE))){

            }
            else {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_PERMISSION);
            }
        } else{
            BOOLEAN_PERMISSION = true;
            getFile(directory);
            obj_VideoAdapter = new VideoAdapter(getApplicationContext(), fileArrayList);
            obj_VideoAdapter.setHasStableIds(true);
            mRecyclerView.setAdapter(obj_VideoAdapter);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if(requestCode == REQUEST_PERMISSION){
            if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                BOOLEAN_PERMISSION = true;
                getFile(directory);
                obj_VideoAdapter = new VideoAdapter(getApplicationContext(), fileArrayList);
                mRecyclerView.setAdapter(obj_VideoAdapter);
            } else{
                Toast.makeText(this, "Please grant Permission", Toast.LENGTH_SHORT).show();
            }
        }
    }

    public ArrayList<File> getFile(File directory) {
        File[] listFile = directory.listFiles();
        if(listFile!=null && listFile.length>0){
            for (File file : listFile) {
                if (file.isDirectory()) {
                    getFile(file);
                } else {
                    BOOLEAN_PERMISSION = false;
                    if (file.getName().endsWith(".mp4") || file.getName().endsWith(".m4a") || file.getName().endsWith(".m4v") || file.getName().endsWith(".f4a") || file.getName().endsWith(".f4v") || file.getName().endsWith(".mp4") || file.getName().endsWith(".m4b") || file.getName().endsWith(".m4r") || file.getName().endsWith(".mp4") || file.getName().endsWith(".f4b") || file.getName().endsWith(".mov") || file.getName().endsWith(".3gp") || file.getName().endsWith(".3gp2") || file.getName().endsWith(".3g2") || file.getName().endsWith(".3gpp") || file.getName().endsWith(".3gpp2") || file.getName().endsWith(".3gp") || file.getName().endsWith(".ogg") || file.getName().endsWith(".oga") || file.getName().endsWith(".ogv") || file.getName().endsWith(".ogx") || file.getName().endsWith(".wmv") || file.getName().endsWith(".wma") || file.getName().endsWith(".asf*") || file.getName().endsWith(".webm") || file.getName().endsWith(".flv") || file.getName().endsWith(".avi") || file.getName().endsWith(".mkv") || file.getName().endsWith(".flv") || file.getName().endsWith(".vob") || file.getName().endsWith(".drc") || file.getName().endsWith(".gif") || file.getName().endsWith(".gifv") || file.getName().endsWith(".mng") || file.getName().endsWith(".MTS") || file.getName().endsWith(".MT2S") || file.getName().endsWith(".TS") || file.getName().endsWith(".mov") || file.getName().endsWith(".qt") || file.getName().endsWith(".wmv") || file.getName().endsWith(".yuv") || file.getName().endsWith(".rm") || file.getName().endsWith(".mvb") || file.getName().endsWith(".amv") || file.getName().endsWith(".mpg") || file.getName().endsWith(".mp2") || file.getName().endsWith(".mpeg") || file.getName().endsWith(".mpe") || file.getName().endsWith(".mpv") || file.getName().endsWith(".xvi") || file.getName().endsWith(".mxf") || file.getName().endsWith(".roq") || file.getName().endsWith(".nsv") || file.getName().endsWith(".3gp")) {
                        for (int j = 0; j < fileArrayList.size(); j++) {
                            if (fileArrayList.get(j).getName().equals(file.getName())) {
                                BOOLEAN_PERMISSION = true;
                            }
                        }
                        if (BOOLEAN_PERMISSION) {
                            BOOLEAN_PERMISSION = false;
                        } else {
                            fileArrayList.add(file);
                        }
                    }
                }
            }
        }
        return fileArrayList;
    }
}

1 Ответ

0 голосов
/ 13 октября 2019

глиссада

implementation 'com.github.bumptech.glide:glide:3.8.0'

затем Вы можете использовать ниже код

Glide.with(this).load(videoArrayList.get(i).
thumbnail(0.2f).into(videoViewHolder.vImageView) 

0,2f - это sizeMultiplier, вы можете настроить его согласно вашему требованию.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...