android更新seekbar与处理程序和runnable

时间:2015-05-21 00:37:48

标签: java android runnable android-handler

我通过添加“seekHandler.post(updateSeekBarTime);”修复了我的问题。正好在我初始化处理程序的地方。

我没有收到错误,但我的代码似乎没有工作,我不确定为什么。任何帮助,将不胜感激。我正试图让一个搜索栏随着媒体播放器播放它的文件而移动。我一直想弄清楚几个小时什么是错的,我很难过。这是我的代码:

public class SongsFragment extends Fragment {

    private ListView songListView;
    private ArrayList<Song> songList;
    private MediaPlayer mp = new MediaPlayer();

    private TextView textView;
    private Button pause;
    private SeekBar seekBar;

    private Handler seekHandler;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        songList = getSongList();
        Collections.sort(songList);

        View rootView = inflater.inflate(R.layout.songs_layout, container, false);
        songListView = (ListView) rootView.findViewById(R.id.listSongs);
        songListView.setAdapter(new SongAdapter(this.getActivity(), songList));

        pause = (Button) rootView.findViewById(R.id.buttonPause);
        textView = (TextView) rootView.findViewById(R.id.textView);
        seekBar = (SeekBar) rootView.findViewById(R.id.seekBar);

        songListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Song song = (Song) parent.getItemAtPosition(position);
                textView.setText(song.getName()+" - "+song.getArtist());

                try {
                    mp.reset();
                    mp.setDataSource(song.getPath());
                    mp.prepare();
                    mp.start();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                Toast.makeText(getActivity(), song.getPath(), Toast.LENGTH_SHORT).show();
            }
        });

        pause.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mp.isPlaying()) {
                    mp.pause();
                    pause.setText("play");
                } else {
                    mp.start();
                    pause.setText("pause");
                }
            }
        });

        seekHandler = new Handler();

        return rootView;
    }

    //handler to change seekBarTime
    private Runnable updateSeekBarTime = new Runnable() {
        public void run() {
            seekBar.setMax(mp.getDuration());
            seekBar.setProgress(mp.getCurrentPosition());
            seekHandler.postDelayed(updateSeekBarTime, 1000);
        }
    };

    public ArrayList<Song> getSongList() {
        //not important
    }
}

0 个答案:

没有答案