Android 사용자 정의 view 카운트다운 컨트롤 실현

본 사례 는 안 드 로 이 드 사용자 정의 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 ? String.valueOf(day) : "0" + day;
       String hourStr = hour >= 10 ? String.valueOf(hour) : "0" + hour;
       String minuteStr = minute >= 10 ? String.valueOf(minute) : "0" + minute;
       String secondStr = second >= 10 ? 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'
여러분,댓 글 환영 합 니 다.
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기