如何在每行Recyclerview中使用搜索欄

[英]How to use seek bar in each row of recyclerview


I have a situation where I need to show seekbar in every row of recylerview to download the media(Audio). The file is downlaoding successfully but everytime I click the downlaod button , only the last seekbar of the recylerview work not the seekbar associated with the particular row.

我有一種情況,我需要在recylerview的每一行顯示搜索欄以下載媒體(音頻)。該文件成功下載,但每次單擊下載按鈕時,只有recylerview的最后一個搜索欄才能與特定行關聯的搜索欄工作。

This is my adapter from where I am downloading audio

這是我正在下載音頻的適配器

public class ListenTestAdapter extends RecyclerView.Adapter<ListenTestAdapter.MyViewHolder> implements AdapterView.OnItemClickListener, View.OnClickListener, View.OnTouchListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnBufferingUpdateListener {

    private static final int DOWNLOAD_THREAD_POOL_SIZE = 1;
    private final Handler handler = new Handler();
    public TextView testNameTextview, downloadTextView, seekBarTextView;
    MyDownloadDownloadStatusListenerV1 myDownloadStatusListener = new MyDownloadDownloadStatusListenerV1();
    int downloadId1;
    private List<Listen> list = new ArrayList<>();
    private Activity context;
    private MediaPlayer mediaPlayer;
    private SeekBar seekBarProgress;
    private int mediaFileLengthInMilliseconds;
    private String mp3Url;
    private Handler durationHandler = new Handler();
    private TextView duration;
    private int timeElapsed;
    private ThinDownloadManager downloadManager;
    private String fileName;
    private RetryPolicy retryPolicy ;
    private   File filesDir ;
    private Uri downloadUri ;
    private SeekBar seekBar ;
    //handler to change seekBarTime
    private Runnable updateSeekBarTime = new Runnable() {
        public void run() {
            //get current position
            timeElapsed = mediaPlayer.getCurrentPosition();
            //set seekbar progress
            //seekbar.setProgress((int) timeElapsed);
            //set time remaing
            double timeRemaining = mediaFileLengthInMilliseconds - timeElapsed;
            duration = (TextView) context.findViewById(R.id.duration);
            //222067.0
            duration.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining), TimeUnit.MILLISECONDS.toSeconds((long) timeRemaining) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining))));

            //repeat yourself that again in 100 miliseconds
            durationHandler.postDelayed(this, 100);
        }
    };


    public ListenTestAdapter(Activity context, List<Listen> list) {

        this.list = list;
        this.context = context;
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
        Toast.makeText(context, "You Clciked " + position, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
        // buttonPlayPause.setImageResource(R.drawable.button_pause);
        durationHandler.postDelayed(updateSeekBarTime, 100);
        mediaFileLengthInMilliseconds = mediaPlayer.getDuration();

        primarySeekBarProgressUpdater();
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onCompletion(MediaPlayer mp) {

        context.findViewById(R.id.mediaPlayerLayout).setVisibility(View.GONE);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return false;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // create a new view
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.listview_listen_item, parent, false);
        // set the view's size, margins, paddings and layout parameters
        MyViewHolder vh = new MyViewHolder(v);
        return vh;
    }

    @Override
    public void onBindViewHolder(final MyViewHolder holder, final int position) {

        testNameTextview.setText(list.get(position).getPassages());
        seekBar.setMax(100);
        seekBar.setProgress(0);
        downloadManager = new ThinDownloadManager(DOWNLOAD_THREAD_POOL_SIZE);
        retryPolicy = new DefaultRetryPolicy();
        filesDir = context.getExternalFilesDir(Environment.DIRECTORY_MUSIC);


        downloadTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mp3Url = list.get(position).getQuestionGroupFile();
                mp3Url = mp3Url.replace(" ", "%20");

                if(!"".equals(mp3Url)){
                    downloadUri = Uri.parse(mp3Url);
                    fileName = mp3Url.substring(mp3Url.lastIndexOf('/') + 1);
                    //download audio
                    downLoadAudio();
                }else{
                    Toast.makeText(context, "Audio is not avialable", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    private void downLoadAudio() {

        Uri destinationUri = Uri.parse(filesDir + "/" + fileName);
        final DownloadRequest downloadRequest = new DownloadRequest(downloadUri)
                .setDestinationURI(destinationUri).setPriority(DownloadRequest.Priority.LOW)
                .setRetryPolicy(retryPolicy)
                .setDownloadContext("Download1")
                .setStatusListener(myDownloadStatusListener);

        if (downloadManager.query(downloadId1) == DownloadManager.STATUS_NOT_FOUND) {

            fileName = fileName.replace("%20", " ");
            downloadId1 = downloadManager.add(downloadRequest);

        } else {
            Toast.makeText(context, "Please wait....Downloading is in progress", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * Method which updates the SeekBar primary progress by current song playing position
     */
    private void primarySeekBarProgressUpdater() {
        seekBarProgress.setProgress((int) (((float) mediaPlayer.getCurrentPosition() / mediaFileLengthInMilliseconds) * 100)); // This math construction give a percentage of "was playing"/"song length"
        if (mediaPlayer.isPlaying()) {
            Runnable notification = new Runnable() {
                public void run() {
                    primarySeekBarProgressUpdater();
                }

            };
            handler.postDelayed(notification, 1000);
        }
    }

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

    private String getBytesDownloaded(int progress, long totalBytes) {
        //Greater than 1 MB
        long bytesCompleted = (progress * totalBytes) / 100;
        if (totalBytes >= 1000000) {
            return ("" + (String.format("%.1f", (float) bytesCompleted / 1000000)) + "/" + (String.format("%.1f", (float) totalBytes / 1000000)) + "MB");
        }
        if (totalBytes >= 1000) {
            return ("" + (String.format("%.1f", (float) bytesCompleted / 1000)) + "/" + (String.format("%.1f", (float) totalBytes / 1000)) + "Kb");

        } else {
            return ("" + bytesCompleted + "/" + totalBytes);
        }
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {


        public MyViewHolder(View view) {
            super(view);
            testNameTextview = (TextView) view.findViewById(R.id.testNameTextview);
            downloadTextView = (TextView) view.findViewById(R.id.downloadTextview);
            seekBarTextView = (TextView) context.findViewById(R.id.duration);
            seekBar = (SeekBar) view.findViewById(R.id.seekBar);

        }
    }

    class MyDownloadDownloadStatusListenerV1 implements DownloadStatusListenerV1 {

        @Override
        public void onDownloadComplete(DownloadRequest request) {
            final int id = request.getDownloadId();
            if (id == downloadId1) {
                seekBarTextView.setText("Downaloaded" + " Audio: " + fileName + " Completed");

                //when download is complete encryption will start
                EncryptDownloadedAudio.encrypt(context,mp3Url,fileName);
            }
        }

        @Override
        public void onDownloadFailed(DownloadRequest request, final int errorCode, final String errorMessage) {
            final int id = request.getDownloadId();
            if (id == downloadId1) {

                context.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        seekBarTextView.setText("Failed to download: " + fileName + " Failed: ErrorCode " + errorCode + ", " + errorMessage);
                        seekBar.setProgress(0);

                    }
                });
            }
        }

        @Override
        public void onProgress(DownloadRequest request, long totalBytes, long downloadedBytes, int progress) {
            int id = request.getDownloadId();

            System.out.println("######## onProgress ###### " + id + " : " + totalBytes + " : " + downloadedBytes + " : " + progress);
            if (id == downloadId1) {
                seekBarTextView.setText("Downloading: " + fileName + ", " + progress + "%" + "  " + getBytesDownloaded(progress, totalBytes));
                seekBar.setProgress(progress);
            }
        }
    }
}

1 个解决方案

#1


-2  

Check the concept of view tags, that will help you out. basically do a seekbar.setTag("UNIQUE ID FOR EVERY VIEW"); then while updating the seekbar use findViewWithTag("UNIQUE ID FOR PARTICULAR VIEW")

檢查視圖標簽的概念,這將有助於您。基本上做一個seekbar.setTag(“每個視圖的唯一ID”);然后在更新搜索欄時使用findViewWithTag(“特殊視圖的獨特ID”)

since you are fetching view by id it will only give the last view with that id.

因為你是通過id獲取視圖,所以它只會給出帶有該id的最后一個視圖。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2016/05/25/725e46c2c4ee12a11e19162fca621ea4.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com