SeekBar

来源:互联网 发布:win10软件锁许可管理器 编辑:程序博客网 时间:2024/06/06 10:02

SeekBar播放进度条,我们使用SeekBar时,可以使用系统自带的样式,当然也可以自定义

自定义的SeekBar进度条样式 是layer_list标签

这里我写了一个播放本地音乐的的SeekBar

效果图:


以下是具体实现代码:代码中有注释

MainActivity:在本地获取音乐

public class MainActivity extends AppCompatActivity {    ContentResolver resolver;    ArrayList<MusicContent> arrayList;    ListView lv;    private MusicAdapter musicAdapter;    MyApplication app;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_listview);        lv = (ListView) findViewById(R.id.lv_music);        app= (MyApplication) getApplication();        arrayList = new ArrayList<>();        resolver = getContentResolver();        init();    }    private void init() {        /**         * 参数一:Uri uri         * 参数二:String[] projection  列名         * 参数三:String selection 查询条件         * 参数四:String[] selectionArgs  查询条件的值         * 参数五:String sortOrder 排序         */        Cursor cursor = resolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);        if (cursor != null) {            while (cursor.moveToNext()) {                String title = cursor.getString(cursor.getColumnIndex("title"));                String _data = cursor.getString(cursor.getColumnIndex("_data"));                arrayList.add(new MusicContent(title, _data));            }            app.arrayList_music.addAll(arrayList);        }        musicAdapter = new MusicAdapter(this, arrayList);        lv.setAdapter(musicAdapter);        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {            @Override            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {                Intent intent = new Intent(MainActivity.this, Activity_Sing.class);                intent.putExtra("title", arrayList.get(position).getTitle().toString());                intent.putExtra("_data", arrayList.get(position).get_data().toString());                startActivity(intent);            }        });    }}
Activity_Sing

整个播放流程
          1.点击播放  再次点击按钮 暂停播放
          2.设置时间为S
          3.新建一个名字为utils包
          4.在utils下创建一个OtherUtils的类
          5.创建Timer定时器,让进度条跟着音乐的播放而向前移动


public class Activity_Sing extends Activity {    TextView tv_sing,text_now_time,text_total_time;    Button but_bo,but_newMusic;    Intent intent;    String _data;    private MediaPlayer mp;    SeekBar seekBar;    Boolean isPlaying=false;    Timer timer;    MyApplication app;    @Override    protected void onCreate(@Nullable Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_sing);        app= (MyApplication) getApplication();        intent = getIntent();        tv_sing = (TextView) findViewById(R.id.tv_sing);        tv_sing.setText(intent.getStringExtra("title"));        /**拿到路径进行播放*/        _data = intent.getStringExtra("_data");        /**创建MediaPlayer对象*/        mp = new MediaPlayer();        try {            mp.setDataSource(_data);//设置播放源            mp.prepare();//准备        } catch (IOException e) {            e.printStackTrace();        }        initView();        /**监听seekBar拖动进度条确定播放的进度*/       seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {            @Override            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {            }            @Override            public void onStartTrackingTouch(SeekBar seekBar) {            }            /**停止拖动时响应*/            @Override            public void onStopTrackingTouch(SeekBar seekBar) {                mp.seekTo(seekBar.getProgress());//设置对应进度条的音乐进度  Progress进度条的进度            }        });        /**播放完成后自动播放下一首*/        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {            @Override            public void onCompletion(MediaPlayer mp) {                nextMusic();            }        });    }    private void initView() {        but_newMusic= (Button) findViewById(R.id.but_nextMusic);        but_newMusic.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                /**播放下一曲*/                nextMusic();            }        });        text_now_time= (TextView) findViewById(R.id.text_now_time);        text_total_time= (TextView) findViewById(R.id.text_total_time);        seekBar = (SeekBar) findViewById(R.id.seekBar);        but_bo = (Button) findViewById(R.id.but_bo);        but_bo.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                /**如果isPlaying=true  正在播放  按下按钮后  暂停                 * 如果isPlaying=false  正在暂停  按下按钮后播放  */                if(!isPlaying){                but_bo.setText("暂停");                        /**注意:直接通过getDuration()获取总时长,一定要等它准备好了才调用这个方法*/                        seekBar.setMax(mp.getDuration());//设置最大时长                        text_total_time.setText(OtherUtils.msToS(mp.getDuration()));//获取总时长                        /**定时器Timer                         * 1.创建定时器对象                         * 2.规定任务*/                        timer=new Timer();                        /**                         * 每隔一秒设置一个seekBar的进度,刷新播放的时间                         *Timer Task task:任务                         * Date firstTime:多少秒后开启定时器                         *long period 每隔多少秒执行依次                         */                        TimerTask timerTask=new TimerTask() {                        @Override                        public void run() {                            /**设置seekBar的进度                             * 1.通过MediaPlayer获取当前歌曲的进度                             * 2.通过seekBar的setProgress设置                             * seekBar更新进度不算刷新UI*/                            final int index= mp.getCurrentPosition();                            seekBar.setProgress(index);                            /**刷新UI*/                            runOnUiThread(new Runnable() {                                @Override                                public void run() {                                    text_now_time.setText(OtherUtils.msToS(index));                                }                            });                        }                    };                    timer.schedule(timerTask,0,1000);                    mp.start();//开始                    isPlaying=true;                }else{                    but_bo.setText("播放");                    mp.pause();//暂停                    isPlaying=false;                }            }        });    }    @Override    protected void onDestroy() {        super.onDestroy();        mp.stop();//停止        mp.release();//释放资源        mp=null;    }    /**随机播放*/    public void nextMusic(){//        mp.stop();//停止上一首歌//        mp.release();//释放资源        mp.reset();//将MediaPlayer回到最初状态        /**         * 怎么拿到要播放的歌:         * 需要总的集合         * 方式1.将集合定义为static         * 方式2.通过Application来管理集合(Application管理整个工程里面共用的资源)*/        //随机产生int值        int index=new Random().nextInt(app.arrayList_music.size());                try {  mp.setDataSource(app.arrayList_music.get(index).get_data());//设置下一首随机播放的歌曲                mp.prepare();//准备                seekBar.setMax(mp.getDuration());//设置最大时长                mp.start();//开始                tv_sing.setText(app.arrayList_music.get(index).getTitle());//更改当前的歌名                text_total_time.setText(OtherUtils.msToS(mp.getDuration()));//更改总时长        } catch (IOException e) {            e.printStackTrace();    }   }}
OtherUtils:

public class OtherUtils {    /**毫秒转分钟*/    public static String msToS(int ms) {        if(ms/1000%60<10){            return ms/1000/60+":0"+ms/1000%60;        }else{            return ms/1000/60+":"+ms/1000%60;        }    }}
MyApplication:

这个自定义MyApplication类,可以拿到对象里面所需要的方法

/** * 在AndroidManifest中的application中添加一个属性 *android:name=".app.MyApplication" */public class MyApplication extends Application {    /**管理音乐的集合*/   public ArrayList<MusicContent> arrayList_music;    @Override    public void onCreate() {        super.onCreate();        arrayList_music=new ArrayList<>();    }}
MusicAdapter:

public class MusicAdapter extends BaseAdapter {    Context context;    LayoutInflater mInflater;    ArrayList<MusicContent> arrayList;    public MusicAdapter(Context context, ArrayList<MusicContent> arrayList) {        this.context = context;        this.arrayList = arrayList;        this.mInflater = LayoutInflater.from(context);    }    @Override    public int getCount() {        return arrayList.size();    }    @Override    public Object getItem(int position) {        return arrayList.get(position);    }    @Override    public long getItemId(int position) {        return position;    }    @Override    public View getView(int position, View convertView, ViewGroup parent) {        ViewHolder viewHolder;        if (convertView == null) {            convertView = mInflater.inflate(R.layout.activity_main, null);            viewHolder = new ViewHolder();            viewHolder.tv_musicSing= (TextView) convertView.findViewById(R.id.tv_musicSing);            viewHolder.tv_number= (TextView) convertView.findViewById(R.id.tv_number);            convertView.setTag(viewHolder);        }        viewHolder = (ViewHolder) convertView.getTag();        MusicContent musicContent = (MusicContent) getItem(position);        viewHolder.tv_musicSing.setText(musicContent.getTitle());        viewHolder.tv_number.setText(musicContent.get_data());        return convertView;    }}class ViewHolder {    TextView tv_musicSing,tv_number;}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:orientation="vertical"    >        <LinearLayout            android:layout_width="match_parent"            android:layout_height="0dp"            android:layout_marginTop="10dp"            android:layout_weight="1"            android:orientation="horizontal"            android:layout_marginLeft="10dp"            android:layout_marginRight="10dp"            android:background="@drawable/shape_music"            >            <LinearLayout                android:layout_width="0dp"                android:layout_height="wrap_content"                android:layout_gravity="center"                android:layout_marginLeft="10dp"                android:layout_weight="0.4"                android:orientation="vertical">                <LinearLayout                    android:layout_width="wrap_content"                    android:layout_height="wrap_content"                    android:orientation="horizontal">                    <TextView                        android:id="@+id/tv_musicSing"                        android:layout_width="match_parent"                        android:layout_height="match_parent"                        android:layout_gravity="center"                        android:gravity="bottom"                        android:textSize="10sp" />                </LinearLayout>                <TextView                    android:id="@+id/tv_number"                    android:layout_width="wrap_content"                    android:layout_height="0dp"                    android:layout_weight="0.5"                    android:textSize="10sp" />            </LinearLayout>        </LinearLayout>    </LinearLayout>


activity_listview.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:background="#e0ffff"    android:orientation="vertical">    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginTop="10dp"        android:orientation="horizontal">        <ImageView            android:id="@+id/listView_iv"            android:layout_width="20dp"            android:layout_height="30dp"            android:layout_marginLeft="10dp"            android:background="@mipmap/xiaoyu"            android:gravity="center" />        <TextView            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:gravity="center"            android:text="歌手"            android:textColor="#ff6c67"            android:textSize="25sp" />    </LinearLayout>    <ListView        android:id="@+id/lv_music"        android:layout_width="match_parent"        android:layout_height="match_parent"></ListView></LinearLayout>
activity_sing.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:orientation="vertical"    >    <TextView        android:id="@+id/tv_sing"        android:layout_marginLeft="10dp"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:textSize="20sp"       />    <LinearLayout        android:layout_width="match_parent"        android:layout_height="0dp"        android:layout_marginTop="10dp"        android:layout_weight="1"        android:orientation="horizontal"        android:layout_marginLeft="10dp"        android:layout_marginRight="10dp"        android:background="@drawable/shape_music"        >        <LinearLayout            android:layout_width="0dp"            android:layout_height="wrap_content"            android:layout_gravity="center"            android:layout_marginLeft="10dp"            android:layout_weight="0.4"            android:orientation="vertical">            <LinearLayout                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:orientation="horizontal">                <TextView                    android:id="@+id/tv_music"                    android:layout_width="match_parent"                    android:layout_height="match_parent"                    android:layout_gravity="center"                    android:gravity="bottom"                    android:textSize="10sp" />            </LinearLayout>            <TextView                android:id="@+id/tv_Sing"                android:layout_width="wrap_content"                android:layout_height="0dp"                android:layout_weight="0.5"                android:textSize="10sp" />        </LinearLayout>    </LinearLayout>    <SeekBar        android:id="@+id/seekBar"        android:layout_width="match_parent"        android:layout_height="wrap_content"        />    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="horizontal">        <TextView            android:id="@+id/text_now_time"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="1"            android:textSize="20sp"            android:layout_marginLeft="20dp"            />        <TextView            android:layout_width="match_parent"            android:layout_height="match_parent"            android:layout_weight="1"/>        <TextView            android:id="@+id/text_total_time"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="2"            android:textSize="20sp"            android:layout_marginRight="20dp"            />    </LinearLayout>    <Button        android:id="@+id/but_bo"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="播放" />    <Button        android:id="@+id/but_nextMusic"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="随机播放" /></LinearLayout>
shape_music.xml

<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"><corners android:radius="10dp"/>    <solid android:color="#ffcccc"/></shape>

这样这个程序就完成了,如果大家还有更好的建议,可以分享一下哟(^U^)ノ~YO



原创粉丝点击