gpt4 book ai didi

android - 如何在某些索引处用不同颜色标记水平 ProgressBar,就像 Android 中的 Youtube 视频黄色广告标记一样

转载 作者:行者123 更新时间:2023-12-04 02:22:04 27 4
gpt4 key购买 nike

在我当前的应用程序中,需要创建自定义视频播放器,特殊要求是在某个给定时间索引显示或标记具有不同颜色的视频进度条,就像 Youtube 用黄色标记其视频以指示其视频上的广告进度条。

为了更清楚,请查看下面的屏幕截图:

enter image description here

此刻,我使用 VideoView 完成了视频播放器功能,现在,我正在使用 Horizo​​ntal ProgressBar 来显示视频进度。我做了很多研究,但不幸的是到目前为止还没有结果。没有强制只使用 Horizo​​ntal ProgressBar,我们也可以使用 SeekBar 或内置 MediaController,但问题是我们应该能够在某个给定位置用不同的颜色标记它。以下是我到目前为止编写的代码:

activity_main.xml

<RelativeLayout 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:background="#000000"
android:paddingLeft="5dp"
android:paddingTop="5dp"
android:paddingRight="5dp"
android:paddingBottom="5dp"
tools:context=".MainActivity">

<VideoView
android:id="@+id/myVideo"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerInParent="true" />

<RelativeLayout
android:id="@+id/rlVidProgress"
android:layout_width="match_parent"
android:layout_alignParentBottom="true"
android:layout_height="wrap_content">

<TextView
android:id="@+id/tvCurrentTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:layout_marginRight="20dp"
android:text="00:00"
android:textColor="@android:color/white"
android:textSize="13dp"
android:textStyle="bold" />

<ProgressBar
android:id="@+id/videoProgress"
style="@android:style/Widget.ProgressBar.Horizontal"
android:layout_centerVertical="true"
android:layout_toLeftOf="@+id/tvTotalTime"
android:layout_width="fill_parent"
android:layout_toRightOf="@+id/tvCurrentTime"
android:layout_height="10dp"
android:layout_marginBottom="10dp" />

<TextView
android:id="@+id/tvTotalTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="5dp"
android:text="00:00"
android:textColor="@android:color/white"
android:textSize="13dp"
android:textStyle="bold" />

</RelativeLayout>

<TextView
android:id="@+id/tvAutoSave"
android:layout_width="wrap_content"
android:textColor="@android:color/white"
android:layout_alignParentRight="true"
android:layout_marginBottom="10dp"
android:text="@string/click_to_auto_save_offer"
android:background="@drawable/white_border_bg"
android:textSize="13dp"
android:layout_above="@+id/rlVidProgress"
android:visibility="gone"
android:paddingBottom="3dp"
android:paddingTop="3dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textStyle="bold"
android:layout_height="wrap_content" />

</RelativeLayout>

MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener
{
ProgressBar videoProgress;
TextView tvCurrentTime;
Handler handler;
VideoView vidView;
String strTotalDuration;
TextView tvAutoSave;
Animation animFadeIn, animFadeOut;

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

animFadeIn = new AlphaAnimation(0, 1);
animFadeIn.setInterpolator(new DecelerateInterpolator()); //add this
animFadeIn.setDuration(1000);

animFadeOut = new AlphaAnimation(1, 0);
animFadeOut.setInterpolator(new AccelerateInterpolator()); //and this
//animFadeOut.setStartOffset(500);
animFadeOut.setDuration(500);


tvCurrentTime = (TextView) findViewById(R.id.tvCurrentTime);
final TextView tvTotalTime = (TextView) findViewById(R.id.tvTotalTime);
tvAutoSave = (TextView) findViewById(R.id.tvAutoSave);
tvAutoSave.setOnClickListener(this);

vidView = (VideoView)findViewById(R.id.myVideo);

videoProgress = (ProgressBar) findViewById(R.id.videoProgress);
videoProgress.setProgress(0);
videoProgress.setMax(100);

final String videoSource = "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4";
vidView.setKeepScreenOn(true);
vidView.setVideoURI(Uri.parse(videoSource));
vidView.setMediaController(null);

handler = new Handler();
// Define the code block to be executed
final Runnable runnableCode = new Runnable() {
@Override
public void run()
{
updateCurrentTime();
// Repeat this the same runnable code block again another 1 seconds
// 'this' is referencing the Runnable object
handler.postDelayed(this, 1000);
}
};

vidView.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
@Override
public void onCompletion(MediaPlayer mp)
{
if(tvAutoSave.getVisibility() == View.VISIBLE)
{
tvAutoSave.setVisibility(View.GONE);
tvAutoSave.startAnimation(animFadeOut);
}
}
});

vidView.setOnPreparedListener(new MediaPlayer.OnPreparedListener()
{
@Override
public void onPrepared(MediaPlayer mp)
{
vidView.start();
strTotalDuration = msToTimeConverter(vidView.getDuration());
tvTotalTime.setText(""+strTotalDuration);
// Start the initial runnable task by posting through the handler
handler.post(runnableCode);
//startHandler();
}
}


);
}


private void updateCurrentTime()
{
if (videoProgress.getProgress() >= 100)
{
handler.removeMessages(0);
}
String currentPosition = msToTimeConverter(vidView.getCurrentPosition());

String[] strArr = currentPosition.split(":");

if(strArr.length==2 && (strArr[1].equals("06") || strArr[1].equals("6")))
{
Toast.makeText(MainActivity.this, "Trigger success at 6 sec position.......", Toast.LENGTH_SHORT).show();
tvAutoSave.setVisibility(View.VISIBLE);
tvAutoSave.startAnimation(animFadeIn);
}

int progress = vidView.getCurrentPosition() * 100 / vidView.getDuration();
videoProgress.setProgress(progress);

tvCurrentTime.setText(""+currentPosition);
}

String msToTimeConverter(int millis)
{
return String.format("%02d:%02d", TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
}

@Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.tvAutoSave:
tvAutoSave.setVisibility(View.GONE);
tvAutoSave.startAnimation(animFadeOut);
Toast.makeText(MainActivity.this, "Offer(s) saved in wallet successfully", Toast.LENGTH_SHORT).show();
break;
}
}
}

最佳答案

一种可能性是创建自定义 View 。通过这样做,您可以在 Canvas 上准确绘制所需的内容,并且对于自定义进度条 View ,这相当容易。但是,它不如使用内置 View 快,但优点是您可以根据需要完全自定义它。请注意,此代码只是一个草案,表明它是可能的。

我创建了属性,因此可以轻松自定义进度条组件的颜色,并且您可以修改高度。下面的 gif 显示了在底部创建的进度条:

Progress-bar in action

class IndicatorProgressBar(context: Context, attrs: AttributeSet) : View(context, attrs) {
private val TAG = "IndicatorProgressBar"

private var barColor = Color.GRAY
private var barHeight = 25F
private var indicatorColor = Color.CYAN
private var progressColor = Color.GREEN
private val paint = Paint()

lateinit var indicatorPositions: List<Float>
var progress = 0F // From float from 0 to 1
set(state) {
field = state
invalidate()
}

init {
paint.isAntiAlias = true
setupAttributes(attrs)
}

private fun setupAttributes(attrs: AttributeSet?) {
context.theme.obtainStyledAttributes(
attrs, R.styleable.IndicatorProgressBar,
0, 0
).apply {
barColor = getColor(R.styleable.IndicatorProgressBar_barColor, barColor)
barHeight = getFloat(R.styleable.IndicatorProgressBar_barHeight, barHeight)
progress = getFloat(R.styleable.IndicatorProgressBar_progress, progress)
progressColor = getColor(R.styleable.IndicatorProgressBar_progressColor, progressColor)
indicatorColor =
getColor(R.styleable.IndicatorProgressBar_indicatorColor, indicatorColor)
recycle()
}
}

override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
paint.style = Paint.Style.FILL // We will only use FILL for the progress bar's components.
drawProgressBar(canvas)
drawProgress(canvas)
drawIndicators(canvas)
}

/**
* Used to get the measuredWidth from the view as a float to be used in the draw methods.
*/
private fun width(): Float {
return measuredWidth.toFloat()
}

private fun drawProgressBar(canvas: Canvas) {
paint.color = barColor
drawCenteredBar(canvas, 0F, width())
}

private fun drawProgress(canvas: Canvas) {
paint.color = progressColor

val barWidth = (progress) * width()
drawCenteredBar(canvas, 0F, barWidth)
}

private fun drawIndicators(canvas: Canvas) {
paint.color = indicatorColor
indicatorPositions.forEach {
val barPositionCenter = it * width()
val barPositionLeft = barPositionCenter - 3F
val barPositionRight = barPositionCenter + 3F

drawCenteredBar(canvas, barPositionLeft, barPositionRight)
}
}

private fun drawCenteredBar(canvas: Canvas, left: Float, right: Float) {
val barTop = (measuredHeight - barHeight) / 2
val barBottom = (measuredHeight + barHeight) / 2

val barRect = RectF(left, barTop, right, barBottom)
canvas.drawRoundRect(barRect, 50F, 50F, paint)
}

override fun onSaveInstanceState(): Parcelable {
val bundle = Bundle()
bundle.putFloat("progress", progress)
bundle.putParcelable("superState", super.onSaveInstanceState())
return bundle
}

override fun onRestoreInstanceState(state: Parcelable) {
var viewState = state

if (viewState is Bundle) {
progress = viewState.getFloat("progress", progress)
viewState = viewState.getParcelable("superState")!!
}

super.onRestoreInstanceState(viewState)
}

override fun performClick(): Boolean {
super.performClick()
return true
}

override fun onTouchEvent(event: MotionEvent): Boolean {
super.onTouchEvent(event)

Log.d(TAG, "x=${event.x} / ${width()} (${event.x / measuredWidth}%), y=${event.y}")
when (event.action) {
MotionEvent.ACTION_DOWN -> {
return updateProgress(event)
}
MotionEvent.ACTION_MOVE -> {
return updateProgress(event)
}
MotionEvent.ACTION_UP -> {
performClick()
return true
}
}
return false
}

private fun updateProgress(event: MotionEvent): Boolean {
// percent may be outside the range (0..1)
val percent = event.x / width()
val boundedPercent = min(max(percent, 0F), 1F) // not above 1
progress = boundedPercent

invalidate() // Make the view redraw itself
return true
}
}

自定义 View 的属性在 res/values/attrs.xml 中定义
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="IndicatorProgressBar">
<!-- The color of the progressbar (not the progress)-->
<attr name="barColor" format="color" />
<!-- The color of the indicators on the progress bar (such as ads on YouTube)-->
<attr name="indicatorColor" format="color" />
<!-- The color of the progressed time/work of the progressbar-->
<attr name="progressColor" format="color" />
<!-- The initial progress value, a value from 0 to 1 -->
<attr name="progress" format="float"/>
<!-- The height of the progress bar, note that layout_height should be set to a larger
number so the onTouchEvent listener is more easy to trigger-->
<attr name="barHeight" format="float"/>

</declare-styleable>
</resources>

您可以在这样的布局中使用自定义 View :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
android:gravity="bottom"
android:paddingLeft="5dp"
android:paddingTop="5dp"
android:paddingRight="5dp"
android:paddingBottom="5dp"
tools:context=".MainActivity">

<com.yourpackagename.progressbarindicator.IndicatorProgressBar
android:id="@+id/indicatorProgressBar"
android:layout_width="wrap_content"
android:layout_height="25dp"
android:layout_centerVertical="true"
android:foregroundGravity="center"
app:barColor="@color/colorAccent"
app:barHeight="12"
app:indicatorColor="#ffffff"
app:progress="0"
app:progressColor="#11c011" />

</RelativeLayout>

主要 Activity :
class MainActivity : AppCompatActivity() {
private lateinit var indicatorProgressBar: IndicatorProgressBar
private val scope: CoroutineScope = CoroutineScope(Dispatchers.Unconfined)
private val TAG = "MainActivity"

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

indicatorProgressBar = findViewById(R.id.indicatorProgressBar)
indicatorProgressBar.indicatorPositions = listOf(0.13F, 0.34F, 0.57F, 0.85F, 0.92F)

updateCurrentTime()

indicatorProgressBar.setOnClickListener {
if(indicatorProgressBar.progress >= 1F){
updateCurrentTime()
}
}
}

private fun updateCurrentTime() {
scope.launch {
while (indicatorProgressBar.progress <= 1F){
Log.d(TAG, "In while loop")
delay(33)
runOnUiThread{
indicatorProgressBar.progress += 0.003F
Log.d(TAG, "Progress is now: ${indicatorProgressBar.progress}")
}
}

}
}

如果要在 MainActivity 中运行 updateCurrentTime 方法,请将 Kotlin Coroutines 添加到 build.gradle (app) 中的依赖项中:
dependencies {
...

def coroutines_version = "1.3.1"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutines_version"
}

关于android - 如何在某些索引处用不同颜色标记水平 ProgressBar,就像 Android 中的 Youtube 视频黄色广告标记一样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56560247/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com