The preparatory work
Start by writing a class MySeekBar that inherits from SeekBar, and then write a layout that looks like this.
<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"
android:gravity="center"
tools:context=".MainActivity">
<me.maxandroid.seekbar.MySeekBar
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Copy the code
The width of the View
Then log the length of the SeekBar in the onDraw method
@Override
protected synchronized void onDraw(Canvas canvas) {
super.onDraw(canvas);
Log.d(TAG, "onDraw: seekbar's width:" + getWidth());
}
Copy the code
Since I am using a 2880*1440 resolution VIRTUAL machine here, the length is naturally 1440 as shown in the picture below, which is consistent with what we wrotematch_parent
This parameterHowever, when we look at the actual effect, we can see that there is a gap between the SeekBar and the left. What if we want to get the length of the progress bar after removing this gap
The width of the ProgressBar
After a bit of research, we found that we can see the Drawable object in the ProgressBar section of the ProgressBar by calling the getProgressDrawable() method, and then the width of the ProgressBar by calling the getBounds() and width() methods
@Override
protected synchronized void onDraw(Canvas canvas) {
super.onDraw(canvas);
Log.d(TAG, "onDraw: seekbar's width:" + getWidth());
Log.d(TAG, "onDraw: progressbar's width:" + getProgressDrawable().getBounds().width());
}
Copy the code
You can see that this value is actually less than the width of the View mentioned above, and this value is how far you actually drag from left to right in the interface
The length of the ProgressBar in ProgressBar
The above values are not actually the length of the progressbar in the progressbar, because the entire progressbar can be viewed as followsWhen the points in the progressbar slide to the left and right, half of the circle is on the outside of the progressbar, so the top length is actually the length of the progressbar plus the length of a progress point. If we only need to obtain the length of the progressbar, we can use the following method to obtain it
@Override
protected synchronized void onDraw(Canvas canvas) {
super.onDraw(canvas);
Log.d(TAG, "onDraw: seekbar's width:" + getWidth());
Log.d(TAG, "onDraw: progressbar's width:" + getProgressDrawable().getBounds().width());
Log.d(TAG, "onDraw: real progressbar's width"+(getProgressDrawable().getBounds().width()-getThumb().getBounds().width()));
}
Copy the code
The result is shown below
Schematic of SeekBar structure
After looking at the above analysis, we can see that the entire length of SeekBar looks something like thisThe corresponding length in this article is