java - TabLayout - 指示器动画延迟
问题描述
在我的应用程序中,我有带有两个选项卡的 TabLayout:秒表和计时器。当我在这两个选项卡之间切换并且计时器未运行时,一切正常。启动计时器时出现问题,指示器动画延迟。下面的视频演示了这个问题:
https://media.giphy.com/media/xjLnjaQ0NgH0a4yqsO/giphy.gif
我认为这是由 CountDownTimer 中的短 countDownInterwal 引起的。我将它设置为 50。这个值很低,因为我想要平滑的时间指示器(在我的应用程序蓝色大圆圈 - Timer中)。
private void startTimer() {
countDownTimer = new CountDownTimer(timeLeftInMillis, 50) {
@Override
public void onTick(long millisUntilFinished) {
timeLeftInMillis = millisUntilFinished;
updateCountDownText();
mProgressBar1.setProgress((int) (timeLeftInMillis/10));
}
@Override
public void onFinish() {
finishCountDownTimer();
countDownSound.start();
showDialogWhenFinishCountDown();
}
}.start();
}
我该怎么做才能解决这个问题?
解决方案
ACountDownTimer
不是最佳解决方案(一开始整个类都会synchronised
导致直接开销),如果您想要流畅的动画,则不应该手动设置动画。使用 Android 框架提供的功能。
我用ObjectAnimator
了一个非常简单的例子:
基本片段类 - 您最感兴趣的是startStopTimer()
方法:
public class TimerFragment extends Fragment {
public TimerFragment() { }
private static int ONE_MINUTE_MILLIS = (int) TimeUnit.MINUTES.toMillis(1);
private ProgressBar progressBar;
private ObjectAnimator animator;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_timer, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
progressBar = view.findViewById(R.id.progressBar);
progressBar.setMax(ONE_MINUTE_MILLIS);
progressBar.setProgress(ONE_MINUTE_MILLIS);
view.findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startStopTimer();
}
});
}
private void startStopTimer() {
if(animator == null) {
animator = ObjectAnimator.ofInt(progressBar, "progress", ONE_MINUTE_MILLIS, 0);
animator.setDuration(ONE_MINUTE_MILLIS);
animator.setInterpolator(new LinearInterpolator());
animator.start();
} else {
animator.cancel();
animator = null;
progressBar.setProgress(ONE_MINUTE_MILLIS);
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
if(animator != null) {
animator.cancel();
animator = null;
}
}
}
推荐阅读
- objective-c - Objective-c 复制一个强属性
- angular - @Input 变量更改后如何在 Angular 中更新 TinyMCE 编辑器内容?
- javascript - 如何读出并显示用户在输入字段中输入的内容
- git - 如何制作作为映射驱动器安装在外部的 PhpStorm 监视文件(跟踪 Git)
- excel - excel vba的用户登录表单
- django - Django:在日期时间字段上按日期分组
- html - 悬停时未打开引导子菜单
- apache-spark - 来自 ALS 模型的预测聚合 - SPARK 协作过滤
- arrays - 操作 Import-Csv 对象并逐行导出到文本文件
- ios - 如何混淆 Cordova 混合应用程序的 Objective C 代码?