温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Android使用view实现倒计时控件

发布时间:2020-10-28 15:13:14 来源:亿速云 阅读:264 作者:Leah 栏目:开发技术

这篇文章将为大家详细讲解有关Android使用view实现倒计时控件,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

Android使用view实现倒计时控件

Android使用view实现倒计时控件

直接上代码

自定义TextView

文字展示

public class StrokeTextView extends TextView {

 private TextView borderText = null;///用于描边的TextView
 private Context mContext;

 public StrokeTextView(Context context) {
  super(context);
  mContext = context;
  borderText = new TextView(context);
  init();
 }

 public StrokeTextView(Context context, AttributeSet attrs) {
  super(context, attrs);
  mContext = context;
  borderText = new TextView(context, attrs);
  init();
 }

 public StrokeTextView(Context context, AttributeSet attrs, int defStyle) {
  super(context, attrs, defStyle);
  mContext = context;
  borderText = new TextView(context, attrs, defStyle);
  init();
 }

 public void init() {
  TextPaint tp1 = borderText.getPaint();
  tp1.setStrokeWidth(12);         //设置描边宽度
  tp1.setStyle(Paint.Style.STROKE);        //对文字只描边
  //设置自定义字体
  Typeface fromAsset = Typeface.createFromAsset(mContext.getAssets(), "fonts/Alibaba-PuHuiTi-Heavy.ttf");
  borderText.setTypeface(fromAsset, Typeface.ITALIC); //自定义字体 ITALIC斜体
  borderText.setTextColor(Color.parseColor("#F46059")); //设置描边颜色
  borderText.setShadowLayer(3.0F, 2F, 2F, Color.parseColor("#ffd44042")); //设置阴影效果(投影)
  borderText.setGravity(getGravity());
 }

 @Override
 public void setLayoutParams(ViewGroup.LayoutParams params) {
  super.setLayoutParams(params);
  borderText.setLayoutParams(params);
 }

 @Override
 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  CharSequence tt = borderText.getText();

  //两个TextView上的文字必须一致
  if (tt == null || !tt.equals(this.getText())) {
   borderText.setText(getText());
   this.postInvalidate();
  }
  super.onMeasure(widthMeasureSpec, heightMeasureSpec);
  borderText.measure(widthMeasureSpec, heightMeasureSpec);
 }

 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
  super.onLayout(changed, left, top, right, bottom);
  borderText.layout(left, top, right, bottom);
 }

 @Override
 protected void onDraw(Canvas canvas) {
  borderText.draw(canvas);
  super.onDraw(canvas);
 }

}

xml

<LinearLayout 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:background="#F3B243"
 android:layout_height="match_parent"
 tools:context=".countdown.TestCountActivity">

 <RelativeLayout
  android:layout_width="match_parent"
  android:layout_height="wrap_content">
  <com.xiao.test.countdown.StrokeTextView
   android:layout_marginTop="100dp"
   android:id="@+id/tv_test"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:background="@drawable/play_advertising_timer_bg"
   android:paddingLeft="15dp"
   android:textColor="#FFFFFF"
   android:textSize="33sp"
   android:layout_centerHorizontal="true"
   android:layout_gravity="center"
   android:gravity="center_vertical"
   android:textStyle="italic"
   android:typeface="monospace"
   tools:ignore="RtlSymmetry"
   android:paddingStart="15dp" />

 </RelativeLayout>

</LinearLayout>

倒计时帮助类

public class CountDownHelper {

 private OnCountDownListener onCountDownListener;
 private Disposable disposable;
 private long remainingTime;

 public CountDownHelper(long remainingTime) {
  this.remainingTime = remainingTime;
 }

 /**
  * 回收倒计时
  */
 public void destory() {
  if (disposable != null && !disposable.isDisposed()) {
   disposable.dispose();
  }
 }

 /**
  * 开始倒计时
  */
 public void startCompute() {
  Observable.interval(1, TimeUnit.SECONDS)
    .subscribeOn(Schedulers.newThread())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(new Observer<Long>() {
     @Override
     public void onSubscribe(Disposable d) {
      disposable = d;
     }

     @Override
     public void onNext(Long aLong) {
      if (onCountDownListener == null) {
       return;
      }
      remainingTime -= 1000;
      if (remainingTime > 0) {
       int day = (int) (remainingTime / (1000 * 60 * 60 * 24));
       int hour = (int) ((remainingTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
       int minute = (int) ((remainingTime % (1000 * 60 * 60)) / (1000 * 60));
       int second = (int) ((remainingTime % (1000 * 60)) / 1000);
       String dayStr = day >= 10 &#63; String.valueOf(day) : "0" + day;
       String hourStr = hour >= 10 &#63; String.valueOf(hour) : "0" + hour;
       String minuteStr = minute >= 10 &#63; String.valueOf(minute) : "0" + minute;
       String secondStr = second >= 10 &#63; String.valueOf(second) : "0" + second;
       onCountDownListener.countDown(dayStr, hourStr, minuteStr, secondStr);
       if (remainingTime <= 0) {
        onCountDownListener.countDownFinish();
        if (disposable != null && !disposable.isDisposed()) {
         disposable.dispose();
        }
       }
      } else {
       onCountDownListener.countDownFinish();
       if (disposable != null && !disposable.isDisposed()) {
        disposable.dispose();
       }
      }
     }

     @Override
     public void onError(Throwable e) {

     }

     @Override
     public void onComplete() {

     }
    });
 }


 /**
  * 设置倒计时回调监听
  *
  * @param onCountDownListener 倒计时监听
  */
 public void setOnCountDownListener(OnCountDownListener onCountDownListener) {
  this.onCountDownListener = onCountDownListener;
 }

 public interface OnCountDownListener {

  /**
   * 倒计时
   *
   * @param day 天
   * @param hour 小时
   * @param minute 分钟
   * @param second 秒
   */
  void countDown(String day, String hour, String minute, String second);

  /**
   * 倒计时完成
   */
  void countDownFinish();
 }
}

TestCountActivity.java

public class TestCountActivity extends AppCompatActivity {
 private CountDownHelper mCountDownHelper;
 private StrokeTextView mTvTest;

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

  mTvTest = findViewById(R.id.tv_test);

//设置自定义字体
  Typeface fromAsset = Typeface.createFromAsset(getAssets(), "fonts/Alibaba-PuHuiTi-Heavy.ttf");
  mTvTest.setTypeface(fromAsset, Typeface.ITALIC); //自定义字体 ITALIC斜体

  long aLong = 1787;
  mCountDownHelper = new CountDownHelper(aLong * 1000);
  mCountDownHelper.startCompute();
  mCountDownHelper.setOnCountDownListener(new CountDownHelper.OnCountDownListener() {
   @SuppressLint("SetTextI18n")
   @Override
   public void countDown(String day, String hour, String minute, String second) {
    mTvTest.setText(hour + ":" + minute + ":" + second);
   }

   @Override
   public void countDownFinish() {
    Log.d("", "结束倒计时");
    mCountDownHelper.destory();
    //延时跳转
    new Handler(new Handler.Callback() {
     @Override
     public boolean handleMessage(Message msg) {

      Toast.makeText(TestCountActivity.this, "时间到了", Toast.LENGTH_SHORT).show();

      return false;
     }
    }).sendEmptyMessageDelayed(0, 10000);//表示延迟10秒发送任务

   }
  });


 }
}

引入依赖

implementation ‘io.reactivex.rxjava2:rxjava:2.0.1'
implementation ‘io.reactivex.rxjava2:rxandroid:2.0.1'

关于Android使用view实现倒计时控件就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI