android - 如何在recyclerview的每一行中使用搜索栏

标签 android

我有一种情况需要在 recylerview 的每一行中显示搜索栏以下载媒体(音频)。该文件已成功下载,但每次我单击下载按钮时,只有 recylerview 的最后一个搜索栏起作用,而不是与特定行关联的搜索栏。

这是我下载音频的适配器

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);
            }
        }
    }
}

最佳答案

检查 View 标签的概念,这将帮助您。基本上做一个 seekbar.setTag("UNIQUE ID FOR EVERY VIEW");然后在更新搜索栏时使用 findViewWithTag("UNIQUE ID FOR PARTICULAR VIEW")

由于您是通过 ID 获取 View ,因此它只会提供具有该 ID 的最后一个 View 。

关于android - 如何在recyclerview的每一行中使用搜索栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37428877/

相关文章:

ANDROID 添加新包

android - react-native android assembleDebug日志: Unknown source file : warning: string 'catalyst_debugjs' has no default translation

android - 如何在 Android 上执行类似 AffineTransform.transform 的操作?

android - Google Analytics - 列出每个事件标签的事件值

android - UnsupportedMethodException Android Studio(测试版)0.8.6

android - 如何在按下 EditText 时阻止 Scrollview 将背景图像移动到顶部?

android - 为 Android > 4.0 Webkit 的焦点禁用文本输入的矩形(橙色边框)

java - Android:如何让 SearchView 关闭按钮返回 setQueryHint()?

java - 将日期字符串转换为 GMT 日期,但显示的是 EST

android - Android Studio 0.4.2:Gradle项目同步失败错误