溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Android怎么自定義View實(shí)現(xiàn)計(jì)時(shí)文字

發(fā)布時(shí)間:2023-04-26 09:57:01 來(lái)源:億速云 閱讀:78 作者:zzz 欄目:開發(fā)技術(shù)

這篇文章主要介紹了Android怎么自定義View實(shí)現(xiàn)計(jì)時(shí)文字的相關(guān)知識(shí),內(nèi)容詳細(xì)易懂,操作簡(jiǎn)單快捷,具有一定借鑒價(jià)值,相信大家閱讀完這篇Android怎么自定義View實(shí)現(xiàn)計(jì)時(shí)文字文章都會(huì)有所收獲,下面我們一起來(lái)看看吧。

一、XML樣式

首先來(lái)確定XML中的屬性樣式,在attrs.xml中增加如下代碼:

    <!--計(jì)時(shí)文字-->
    <declare-styleable name="TimingTextView">
        <!--倒計(jì)時(shí)-->
        <attr name="countdown" format="boolean" />
        <!--時(shí)間最大值-->
        <attr name="max" format="integer" />
        <!--時(shí)間單位,時(shí):h,分:m,秒:s-->
        <attr name="unit">
            <enum name="h" value="1" />
            <enum name="m" value="2" />
            <enum name="s" value="3" />
        </attr>
    </declare-styleable>

這里的計(jì)時(shí)文字目前有3個(gè)屬性,第一個(gè)boolean用來(lái)確定是計(jì)時(shí)還是倒計(jì)時(shí),第二個(gè)是最大時(shí)間,第三個(gè)是時(shí)間單位:時(shí)分秒。

二、構(gòu)造方法

之前我說(shuō)自定義View有三種方式,一種是繼承View,一種是繼承現(xiàn)有的View,還有一種是繼承ViewGroup,那么今天的這個(gè)計(jì)時(shí)文字,我們就可以繼承現(xiàn)有的View,這樣做的目的就是可以讓我們減少一定的工作量,專注于功能上,下面我們?cè)?code>com.llw.easyview包下新建一個(gè)TimingTextView類,里面的代碼如下所示:

public class TimingTextView extends MaterialTextView {
    /**
     * 時(shí)間單位
     */
    private int mUnit;
    /**
     * 計(jì)時(shí)最大值
     */
    private int mMax;
    /**
     * 是否倒計(jì)時(shí)
     */
    private boolean mCountDown;
    private int mTotal;
    /**
     * 是否計(jì)時(shí)中
     */
    private boolean mTiming;
    public TimingTextView(Context context) {
        this(context, null);
    }
    public TimingTextView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }
    public TimingTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        @SuppressLint("CustomViewStyleable")
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.TimingTextView);
        mCountDown = typedArray.getBoolean(R.styleable.TimingTextView_countdown, false);
        mMax = typedArray.getInteger(R.styleable.TimingTextView_max, 60);
        mUnit = typedArray.getInt(R.styleable.TimingTextView_unit, 3);
        typedArray.recycle();
    }
}

因?yàn)橛杏?jì)時(shí)的緣故,所以我們需要一個(gè)計(jì)時(shí)監(jiān)聽(tīng),主要用于結(jié)束的時(shí)候進(jìn)行調(diào)用,可以在com.llw.easyview下新建一個(gè)TimingListener接口,代碼如下:

public interface TimingListener {
    void onEnd();
}

三、API方法

下面在TimingTextView中新增一些API方法和變量,首先增加變量:

    private TimingListener listener;
    private CountDownTimer countDownTimer;

然后增加API方法:

    /**
     * 設(shè)置時(shí)間單位
     *
     * @param unit 1,2,3
     */
    public void setUnit(int unit) {
        if (unit <= 0 || unit > 3) {
            throw new IllegalArgumentException("unit value can only be between 1 and 3");
        }
        mUnit = unit;
    }
    /**
     * 設(shè)置最大時(shí)間值
     *
     * @param max 最大值
     */
    public void setMax(int max) {
        mMax = max;
    }
    /**
     * 設(shè)置是否為倒計(jì)時(shí)
     *
     * @param isCountDown true or false
     */
    public void setCountDown(boolean isCountDown) {
        mCountDown = isCountDown;
    }
    public void setListener(TimingListener listener) {
        this.listener = listener;
    }
    public boolean isTiming() {
        return mTiming;
    }
    /**
     * 開始
     */
    public void start() {
        switch (mUnit) {
            case 1:
                mTotal = mMax * 60 * 60 * 1000;
                break;
            case 2:
                mTotal = mMax * 60 * 1000;
                break;
            case 3:
                mTotal = mMax * 1000;
                break;
        }
        if (countDownTimer == null) {
            countDownTimer = new CountDownTimer(mTotal, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    int time = 0;
                    if (mCountDown) {
                        time = (int)  (millisUntilFinished / 1000);
                        setText(String.valueOf(time));
                    } else {
                        time = (int) (mTotal / 1000 - millisUntilFinished / 1000);
                    }
                    setText(String.valueOf(time));
                }
                @Override
                public void onFinish() {
                    //倒計(jì)時(shí)結(jié)束
                    end();
                }
            };
            mTiming = true;
            countDownTimer.start();
        }
    }
    /**
     * 計(jì)時(shí)結(jié)束
     */
    public void end() {
        mTotal = 0;
        mTiming = false;
        countDownTimer.cancel();
        countDownTimer = null;
        if (listener != null) {
            listener.onEnd();
        }
    }

代碼還是很簡(jiǎn)單的,你敢信,這個(gè)自定義View就寫完了,不過(guò)可能存在一些問(wèn)題,我將自定義View的代碼都放到了一個(gè)library下面里,然后將這個(gè)library進(jìn)行構(gòu)建成aar,然后上傳到mavenCentral()中。

四、使用

&emsp;&emsp;然后我們修改一下activity_main.xml,代碼如下所示:

<?xml version="1.0" encoding="utf-8"?>
<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:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context=".MainActivity">
    <com.easy.view.MacAddressEditText
        android:id="@+id/mac_et"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:boxBackgroundColor="@color/white"
        app:boxStrokeColor="@color/black"
        app:boxStrokeWidth="2dp"
        app:boxWidth="48dp"
        app:separator=":"
        app:textColor="@color/black"
        app:textSize="16sp" />
    <Button
        android:id="@+id/btn_mac"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:text="獲取地址" />
    <com.easy.view.CircularProgressBar
        android:id="@+id/cpb_test"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        app:maxProgress="100"
        app:progress="10"
        app:progressbarBackgroundColor="@color/purple_500"
        app:progressbarColor="@color/purple_200"
        app:radius="80dp"
        app:strokeWidth="16dp"
        app:text="10%"
        app:textColor="@color/teal_200"
        app:textSize="28sp" />
    <Button
        android:id="@+id/btn_set_progress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:text="隨機(jī)設(shè)置進(jìn)度" />
    <com.easy.view.TimingTextView
        android:id="@+id/tv_timing"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:text="計(jì)時(shí)文字"
        android:textColor="@color/black"
        android:textSize="32sp"
        app:countdown="false"
        app:max="60"
        app:unit="s" />
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="12dp"
        android:gravity="center"
        android:orientation="vertical">
        <CheckBox
            android:id="@+id/cb_flag"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="計(jì)時(shí)" />
        <Button
            android:id="@+id/btn_start"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="開始" />
    </LinearLayout>
</LinearLayout>

下面我們回到MainActivity中,在onCreate()方法中添加如下代碼:

        //計(jì)時(shí)文本操作
        TimingTextView tvTiming = findViewById(R.id.tv_timing);
        CheckBox cbFlag = findViewById(R.id.cb_flag);
        Button btnStart = findViewById(R.id.btn_start);
        tvTiming.setListener(new TimingListener() {
            @Override
            public void onEnd() {
                tvTiming.setText("計(jì)時(shí)文字");
                btnStart.setText("開始");
            }
        });
        cbFlag.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                cbFlag.setText(isChecked ? "倒計(jì)時(shí)" : "計(jì)時(shí)");
            }
        });
        //計(jì)時(shí)按鈕點(diǎn)擊
        btnStart.setOnClickListener(v -> {
            if (tvTiming.isTiming()) {
                //停止計(jì)時(shí)
                tvTiming.end();
                btnStart.setText("開始");
            } else {
                tvTiming.setMax(6);
                tvTiming.setCountDown(cbFlag.isChecked());
                tvTiming.setUnit(3);//單位 秒
                //開始計(jì)時(shí)
                tvTiming.start();
                btnStart.setText("停止");
            }
        });

關(guān)于“Android怎么自定義View實(shí)現(xiàn)計(jì)時(shí)文字”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對(duì)“Android怎么自定義View實(shí)現(xiàn)計(jì)時(shí)文字”知識(shí)都有一定的了解,大家如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI