listview中的Seekbar返回第一个和最后一个位置

时间:2017-01-06 11:29:57

标签: android listview android-seekbar

https://blogs.msdn.microsoft.com/dotnet/2016/09/26/introducing-net-standard/

好吧,我有包含音频文件的listview,音频播放工作正常但搜索栏没有更新,当我点击任何项目时!最后一个位置项搜索栏正在更新和播放。我找不到确切的解决方案。这是我的代码。

public class AudioAdapter extends android.widget.BaseAdapter
{
    final ViewHolder holder;
    Uri uri;
    private Dialog dialog;
    TextView cur_val;
    Activity act;
    private Boolean isButtonClicked=false;
    private LruCache<String, Bitmap> mMemoryCache;
    private Context mcontext;
    AppUtils appUtils;
    MediaPlayer mp=new MediaPlayer();
    ArrayList<HashMap<String, String>> listname;
    ProgressBar pb;
    int downloadedSize = 0;
    int totalSize = 0;
    String media,title;


    public AudioAdapter(Context context,Activity act, ArrayList<HashMap<String, String>> value)
    {
        mcontext=context;
        listname=value;
        this.act = act;

        // Memory Cache
        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        final int cacheSize = maxMemory / 8;
        mMemoryCache = new LruCache<String, Bitmap>(cacheSize)
        {
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                // The cache size will be measured in kilobytes rather than
                // number of items.
                return bitmap.getByteCount() / 1024;
            }
        };

        appUtils = new AppUtils(mcontext);
        holder = new ViewHolder();
    }


    @Override
    public int getCount() {
        return listname.size();
   }

    @Override
    public Object getItem(int position) {
        return listname.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent)
    {


        convertView=View.inflate(mcontext, R.layout.audioreff, null);

        holder.title=(TextView)convertView.findViewById(R.id.audiotitle);
        holder.postedby=(TextView)convertView.findViewById(R.id.postedby);
        holder.postedon=(TextView)convertView.findViewById(R.id.date);
        holder.likes=(TextView)convertView.findViewById(R.id.likes);
        holder.play=(Button)convertView.findViewById(R.id.butplay);
        holder.seekBar=(SeekBar)convertView.findViewById(R.id.seekBar);
        holder.seekBar.setMax(99);
        holder.seekBar.setEnabled(false);

        convertView.setTag(holder);


        HashMap<String, String> result=listname.get(position);

        final String titlee=result.get("title");
        String postedy=result.get("postedby");
        String postedon=result.get("datetime");
        String likes=result.get("likes");
        final String medi=result.get("media");



        holder.title.setText(titlee);
        holder.postedby.setText(postedy);
        holder.postedon.setText(postedon);
        holder.likes.setText(likes);


        holder.play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // isButtonClicked = !isButtonClicked; // toggle the boolean flag
                //   v.setBackgroundResource(isButtonClicked ? R.drawable.buttonplay : R.drawable.pausebutton);
                showProgress();
                media=medi;
                title=titlee;
                Toast.makeText(mcontext,media+position, Toast.LENGTH_SHORT).show();
                Log.d("",AppConstantsUtils.BASE_URL+medi);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    downloadFile();
                }
            }).start();


            }
        });


        return convertView;
    }




    static class ViewHolder
    {
        TextView title,postedby,likes,postedon;
        Button play;
        SeekBar seekBar;
    }


      private void downloadFile(){

        try {
            URL url = new URL(AppConstantsUtils.BASE_URL+media);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);

            //connect
            urlConnection.connect();
            final String folder_main = "Apna";
            //set the path where we want to save the file
         /*   File SDCardRoot =new File(Environment.getExternalStorageDirectory(),folder_main);

            if (!SDCardRoot.exists()) {
                SDCardRoot.mkdirs();
            }

            //create a new file, to save the downloaded file
            File file = new File(SDCardRoot,title);*/



            File wallpaperDirectory = new     File(Environment.getExternalStorageDirectory(),folder_main);
      //have the object build the directory structure, if needed.
            wallpaperDirectory.mkdirs();
    //create a File object for the output file
            final String perfection=title.replaceAll("\"","");
            File outputFile = new File(wallpaperDirectory, perfection+".mp3");
    //now attach the OutputStream to the file object, instead of a String representation






            FileOutputStream fileOutput = new FileOutputStream(outputFile);

            //Stream used for reading the data from the internet
            InputStream inputStream = urlConnection.getInputStream();

            //this is the total size of the file which we are downloading
            totalSize = urlConnection.getContentLength();

            act.runOnUiThread(new Runnable() {
                public void run() {
                    pb.setMax(totalSize);
                }
            });

            //create a buffer...
            byte[] buffer = new byte[1024];
            int bufferLength = 0;

            while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
                fileOutput.write(buffer, 0, bufferLength);
                downloadedSize += bufferLength;
                // update the progressbar //
                act.runOnUiThread(new Runnable() {
                    public void run() {
                        pb.setProgress(downloadedSize);
                        float per = ((float)downloadedSize/totalSize) * 100;
                        cur_val.setText("Downloaded " + downloadedSize + "KB / " + totalSize + "KB (" + (int)per + "%)" );
                    }
               });
            }
            //close the output stream when complete //
            fileOutput.close();
            act.runOnUiThread(new Runnable() {
                public void run() {


                    dialog.dismiss();



                    try{
                    mp.setDataSource(Environment.getExternalStorageDirectory().getPath()+"/Apna/"+perfection+".mp3");//Write your location here
                    mp.prepareAsync();
                  //  mp.start();
                    mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                        @Override
                        public void onPrepared(MediaPlayer mp) {
                            mp.start();
                            mRunnable.run();
                        }
                    });


                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }


        }
        });

    } catch (final MalformedURLException e) {
        showError("Error : MalformedURLException " + e);
        Log.d("dfdsfsd", e.toString());
        e.printStackTrace();
    } catch (final IOException e) {
        Log.d("dfdsfsd", e.toString());
        showError("Error : IOException " + e);
        e.printStackTrace();
    }
    catch (final Exception e) {
        Log.d("dfdsfsd", e.toString());
        showError("Error : Please check your internet connection " + e);
    }
}

private void showError(final String err){
    act.runOnUiThread(new Runnable() {
        public void run() {
            Toast.makeText(mcontext, err, Toast.LENGTH_LONG).show();
            Log.d("dfdsfsd", err);
        }
    });
}

  private void showProgress(){
    dialog = new Dialog(mcontext);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.myprogressdialog);
    dialog.setTitle("Download Progress");


    cur_val = (TextView) dialog.findViewById(R.id.cur_pg_tv);
    cur_val.setText("Starting download...");
    dialog.show();

    pb = (ProgressBar)dialog.findViewById(R.id.progress_bar);
    pb.setProgress(0);
    pb.setProgressDrawable(mcontext.getResources().getDrawable(R.drawable.green_progress));
}




private Handler mHandler = new Handler();
private Runnable mRunnable = new Runnable() {

        @Override
        public void run() {
            if(mp != null) {

                //set max value
                int mDuration = mp.getDuration();
                holder.seekBar.setMax(mDuration);

                //update total time text view

                //set progress to current position
                int mCurrentPosition = mp.getCurrentPosition();
                holder.seekBar.setProgress(mCurrentPosition);

                //update current time text view

                //handle drag on seekbar
                holder.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

                    @Override
                    public void onStopTrackingTouch(SeekBar seekBar) {

                    }

                    @Override
                    public void onStartTrackingTouch(SeekBar seekBar) {

                    }

                    @Override
                    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                        if(mp != null && fromUser){
                            mp.seekTo(progress);
                        }
                    }
                });


            }

            //repeat above code every second
            mHandler.postDelayed(this, 10);
        }
    };
}

2 个答案:

答案 0 :(得分:0)

更改 getView()方法

@Override
public View getView(final int position, View convertView, ViewGroup parent)
{
YourHolder holder=null;
if(convertView==null){
holder=new YourHolder();

convertView=View.inflate(mcontext, R.layout.audioreff, null);

holder.title=(TextView)convertView.findViewById(R.id.audiotitle);
holder.postedby=(TextView)convertView.findViewById(R.id.postedby);
holder.postedon=(TextView)convertView.findViewById(R.id.date);
holder.likes=(TextView)convertView.findViewById(R.id.likes);
holder.play=(Button)convertView.findViewById(R.id.butplay);
holder.seekBar=(SeekBar)convertView.findViewById(R.id.seekBar);
holder.seekBar.setMax(99);
holder.seekBar.setEnabled(false);

convertView.setTag(holder);
}else{
holder=(YourHolder)convertView.getTag();
}

HashMap<String, String> result=listname.get(position);

final String titlee=result.get("title");
String postedy=result.get("postedby");
String postedon=result.get("datetime");
String likes=result.get("likes");
final String medi=result.get("media");



holder.title.setText(titlee);
holder.postedby.setText(postedy);
holder.postedon.setText(postedon);
holder.likes.setText(likes);


holder.play.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // isButtonClicked = !isButtonClicked; // toggle the boolean flag
        //   v.setBackgroundResource(isButtonClicked ? R.drawable.buttonplay : R.drawable.pausebutton);
        showProgress();
        media=medi;
        title=titlee;
        Toast.makeText(mcontext,media+position, Toast.LENGTH_SHORT).show();
        Log.d("",AppConstantsUtils.BASE_URL+medi);
    new Thread(new Runnable() {
        @Override
        public void run() {
            downloadFile();
        }
    }).start();


    }
});


return convertView;

}

  

不要将持有人变量全局化。如果你把它作为全局,那么getView的最后一项值就是保留。在上述情况下,该问题得以解决。只需在列表视图中阅读持有者机制。

这会对你有所帮助

答案 1 :(得分:0)

不要生成适配器的 user_id complete_order order_date complete_order_time_diff <chr> <chr> <date> <time> 1 1 1 2015-01-28 NA days 2 1 1 2015-01-31 3 days 3 1 1 2015-02-23 23 days 4 2 1 2015-01-25 NA days 5 2 1 2015-01-28 3 days 6 2 1 2015-02-21 24 days 个全局变量项的views。因为屏幕上不仅有一个项目。如果您将其设为全局,则ListView的值将填充最后调用these variables的{​​{1}}。

相反,您可以将其保留在list-item getView中,并根据{{array更新相应的views(例如values position) 1}}。

简而言之,您的实施不正确。首先,您需要了解seekBar的工作原理。