Android-SeekBar进度条的使用
在我们使用音乐播放器或者是视频播放器时,下面都会有一个进度条,拖动进度条即可改变
音乐的进度和视频播放的进度,那么在安卓里面也有相应的工具类,它就是SeekBar
制作可拖动的进度条
首先是布局文件
activity_main.xml
使用两个TextView用来显示是否拖动以及拖动到了哪一个位置
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity"
>
<SeekBar
android:id="@+id/id_seekBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"
android:progress="50"
/>
<TextView
android:id="@+id/id_tv1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/id_tv2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
主活动获取组件并且设置监听事件
MainActivity.java
package com.xieth.as.seekbardemo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.SeekBar;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener {
private SeekBar seekBar = null;
private TextView tv1, tv2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
private void initViews() {
seekBar = (SeekBar) findViewById(R.id.id_seekBar);
seekBar.setOnSeekBarChangeListener(this);
tv1 = (TextView) findViewById(R.id.id_tv1);
tv2 = (TextView) findViewById(R.id.id_tv2);
}
// 数值改变
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
tv1.setText("正在拖动");
tv2.setText("当前数值:" + progress);
}
// 开始拖动
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
tv1.setText("开始拖动");
}
// 停止拖动
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
tv1.setText("停止拖动");
}
}
运行:
鼠标有点错位,录制gif软件不好,还是在那个进度条上面的。
自定义SeekBar样式
首先来看一下Android系统自带的样式
<SeekBar
style="@android:style/Widget.SeekBar"
android:id="@+id/id_seekBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"
android:progress="50"
/>
这一句代码
style="@android:style/Widget.SeekBar"
运行:
首先准备两张图片
灰色代表没有拖动的状态,黄色代表正在进行拖动状态
my_style.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@mipmap/select" android:state_pressed="true"
android:state_window_focused="true"></item>
<item android:drawable="@mipmap/normal"></item>
</selector>
然后在布局文件引用即可
<SeekBar
android:thumb="@drawable/my_style"
android:id="@+id/id_seekBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"
android:progress="50"
/>
运行: