自定义控件----倒计时控件

先上效果图:
这里写图片描述
因为时分秒都有自己的背景色等布局,所以重写一个textview 不够灵活,所以我们自定义一个TimeTextView继承自Linearlayout 然后再在里面放几个textview即可。
先看 布局文件吧:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:layout_marginBottom="@dimen/default_margin"
              android:layout_marginLeft="@dimen/default_margin"
              android:layout_marginRight="@dimen/default_margin"
              android:background="@android:color/transparent"
              android:gravity="center"
              android:orientation="horizontal"
              android:padding="@dimen/default_margin_small">

    <TextView
        android:id="@+id/tv_hours"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/background_btn_red"
        android:padding="@dimen/default_margin_small"
        android:text="24"
        android:textColor="@color/white"
        android:textSize="@dimen/text_default"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=":"
        android:textColor="@color/default_text_red"
        android:textSize="@dimen/text_default"/>

    <TextView
        android:id="@+id/tv_minutes"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/background_btn_red"
        android:padding="@dimen/default_margin_small"
        android:text="00"
        android:textColor="@color/white"
        android:textSize="@dimen/text_default"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=":"
        android:textColor="@color/default_text_red"
        android:textSize="@dimen/text_default"/>

    <TextView
        android:id="@+id/tv_seconds"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/background_btn_red"
        android:padding="@dimen/default_margin_small"
        android:text="00"
        android:textColor="@color/white"
        android:textSize="@dimen/text_default"/>
</LinearLayout>

然后就是自定义的linearlayout了,

/**
 * 倒计时 3文本
 * Created By Fangchao On 2015/3/12
 */
public class TimeTextView extends LinearLayout {
    private long mday, mhour, mmin, msecond;//天,小时,分钟,秒
    private boolean run = false; //是否启动了
    Timer timer = new Timer();
    TextView Vhour, Vmin, Vseconds;

    public TimeTextView(Context context) {
        super(context);
        iniUI(context);
    }

    public TimeTextView(Context context, AttributeSet attrs) {

        super(context, attrs);
        iniUI(context);
    }

    public void iniUI(Context context) {
        LayoutInflater mInflater = LayoutInflater.from(context);
        View myView = mInflater.inflate(R.layout.view_time_texviews, null);

        Vhour = (TextView) myView.findViewById(R.id.tv_hours);
        Vmin = (TextView) myView.findViewById(R.id.tv_minutes);
        Vseconds = (TextView) myView.findViewById(R.id.tv_seconds);
        addView(myView);
    }

    public TimeTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        iniUI(context);
    }

    private Handler mHandler = new Handler() {

    };

    public boolean isRun() {
        return run;
    }

    public void setRun(boolean run) {
        this.run = run;
    }

    public void start() {
        if (!isRun()) {
            setRun(true);
            timer.schedule(task, 1000, 1000);
        }
    }

    /**
     * 根据传进来的时间差 为textview 赋值
     *
     * @param duration
     */
    public void setTimes(long duration) {
        Date date = new Date(duration);
        Date date1 = new Date(1L);
        /*mday = duration / 60000 / 60 / 24;
        mhour = (duration - mday * 6000 * 60 * 24) / 3600000;

        mmin = (duration - mhour * 6000 * 60 - mday * 3600000 * 24) / 60000;
        msecond = (duration - mmin * 60000 - mhour * 3600000 - mday * 3600000 * 24) / 60000;*/
//需要修改,测试用
        mday = date.getDay();
        mhour = date.getHours();
        mmin = date.getMinutes();
        msecond = date.getSeconds();
    }

    /**
     * 倒计时计算
     */
    private void ComputeTime() {
        msecond--;
        if (msecond < 0) {
            mmin--;
            msecond = 59;
            if (mmin < 0) {
                mmin = 59;
                mhour--;
                if (mhour < 0) {
                    // 倒计时结束
                    mhour = 24;
                    mday--;
                }
            }
        }
    }

    TimerTask task = new TimerTask() {
        @Override
        public void run() {

            mHandler.post(new Runnable() {      // UI thread
                @Override
                public void run() {
                    run = true;
                    ComputeTime();
                    if (mday < 0) {
                        setVisibility(View.GONE);

                        setRun(false);
                    }
                    Vhour.setText(mhour < 10 ? ("0" + mhour) : mhour + "");
                    Vseconds.setText(msecond < 10 ? ("0" + msecond) : msecond + "");
                    Vmin.setText(mmin < 10 ? ("0" + mmin) : mmin + "");
                }
            });
        }
    };
}

用的时候直接在需要的地方直接把TimeTextview 放上就行了,
举个例子吧,可以在adapter中设置倒计时时长。。。。

   @Override
    public void onBindHeaderView(RecyclerView.ViewHolder holder, int position) {
        HeaderViewHolder headViewHolder = (HeaderViewHolder) holder;

        long duration=  1426244976513L + 200 * 1000 - TimeUtils.getCurrentTimeInLong();
        Log.e("long///", TimeUtils.getCurrentTimeInLong() + "");
        if (!headViewHolder.timeTextView.isRun()) {

            headViewHolder.timeTextView.setTimes(duration);
            headViewHolder.timeTextView.start();
        }
    }
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
WPF 秒表 计时器 定时关机 到计时关机 public const uint WM_SYSCOMMAND = 0x0112; public const uint SC_MONITORPOWER = 0xF170; [DllImport("user32")] public static extern IntPtr SendMessage(IntPtr hWnd, uint wMsg, uint wParam, int lParam); /// /// 关闭显示器 /// public void CloseScreen() { IntPtr windowHandle = Process.GetCurrentProcess().MainWindowHandle; SendMessage(windowHandle, WM_SYSCOMMAND, SC_MONITORPOWER, 2); // 2 为关闭显示器, -1则打开显示器 } using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Threading; using IniFiles; namespace StopWatch { /// /// shutdonwCtrl.xaml 的交互逻辑 /// public partial class shutdonwCtrl : UserControl { DispatcherTimer timer1; DispatcherTimer timer2; public shutdonwCtrl() { InitializeComponent(); timer1 = new DispatcherTimer(); timer1.Tick += new EventHandler(OnTimer1); timer1.Interval = new TimeSpan(0, 0, 1); timer2 = new DispatcherTimer(); timer2.Tick += new EventHandler(OnTimer2); timer2.Interval = new TimeSpan(0, 0, 1); btn_cancel.IsEnabled = false; cancel1.IsEnabled = false; } IniFile INI = new IniFile(IniFile.AppIniName); public void LoadIni() { cbo_hour.Text = INI.ReadString("定时关机", "时", "0"); cbo_Minute.Text = INI.ReadString("定时关机", "分", "0"); cbo_Second.Text = INI.ReadString("定时关机", "秒", "0"); cbo1.Text = INI.ReadString("到计时关机", "分", "0"); //combobox1.Text = INI.ReadString("到计时", "时", "0"); //combobox2.Text = INI.ReadString("到计时", "分", "0"); //combobox3.Text = INI.ReadString("到计时", "秒", "0"); } public void SaveIni() { INI.WriteString("定时关机", "时", cbo_hour.Text); INI.WriteString("定时关机", "分", cbo_Minute.Text); INI.WriteString("定时关机", "秒", cbo_Second.Text); INI.WriteString("到计时关机", "分", cbo1.Text); } private void ShutDown() { System.Diagnostics.Process.Start("shutdown.exe", "-s -t 1"); } private void OnTimer1(object sender,EventArgs e) { if (second > 0) second--; label1.Content = string.Format("Windows将在 {0} 关机", TimerClass.GetTimeString1(second)); if (second <= 0 && !cbo1.IsEnabled) { ShutDown(); } } int second = 0; private void Button_Click(object sender, RoutedEventArgs e) { second = Convert.ToInt32(cbo1.Text) * 60; if (second <= 0) { MessageBox.Show("数值必须大于0!"); return; } timer1.Start(); cbo1.IsEnabled = false; cancel1.IsEnabled = true; start1.IsEnabled = false; } private void Button_Click_1(object sender, RoutedEventArgs e) { label1.Content = " "; timer1.Stop(); second = 0; cbo1.IsEnabled = true; cancel1.IsEnabled = false; start1.IsEnabled = true; } private void OnTimer2(object sender, EventArgs e) { if ( DateTime.Now.Hour == Convert.ToInt32(cbo_hour.Text) && DateTime.Now.Minute == Convert.ToInt32(cbo_Minute.Text) && DateTime.Now.Second == Convert.ToInt32(cbo_Second.Text) ) { ShutDown(); } } private void Button_Click_2(object sender, RoutedEventArgs e) { int s = Convert.ToInt32(cbo_hour.Text) * 3600 + Convert.ToInt32(cbo_Minute.Text) * 60 + Convert.ToInt32(cbo_Second.Text); timer2.Start(); label2.Content = string.Format("Windows将在 {0} 关机", TimerClass.GetTimeString1(s)); btn_start.IsEnabled = false; btn_cancel.IsEnabled = true; cbo_hour.IsEnabled = false; cbo_Minute.IsEnabled = false; cbo_Second.IsEnabled = false; } private void btn_cancel_Click(object sender, RoutedEventArgs e) { label2.Content = ""; timer2.Stop(); btn_start.IsEnabled = true; btn_cancel.IsEnabled = false; cbo_hour.IsEnabled = true; cbo_Minute.IsEnabled = true; cbo_Second.IsEnabled = true; } } } using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Threading.Tasks; using System.Runtime.InteropServices; using System.Windows.Threading; using IniFiles; namespace StopWatch { /// /// TimerCtrl.xaml 的交互逻辑 /// public partial class TimerCtrl : UserControl { private DispatcherTimer timer1 = null; private DispatcherTimer timer2 = null; int SND_SYNC = 0x0000; /* play asynchronously */ //异步 int SND_ASYNC = 0x0001; int SND_LOOP = 8; [DllImport("winmm")] public static extern bool PlaySound(string szSound, IntPtr hMod, int flags); private void playSound3() { Task tsk = new Task(new Action(proc)); tsk.Start(); } private void proc() { PlaySound(@"Sound\2.wav", IntPtr.Zero, SND_SYNC); PlaySound(@"Sound\2.wav", IntPtr.Zero, SND_SYNC); PlaySound(@"Sound\2.wav", IntPtr.Zero, SND_SYNC); } public TimerCtrl() { InitializeComponent(); timer1 = new DispatcherTimer(); timer1.Tick += new EventHandler(OnTimer1); timer1.Interval = new TimeSpan(0, 0, 1); timer2 = new DispatcherTimer(); timer2.Tick += new EventHandler(OnTimer2); timer2.Interval = new TimeSpan(0, 0, 1); btn_reset1.IsEnabled = false; btn_pause1.IsEnabled = false; } int h = 0; int m = 0; int s = 0; int seconds = 0; private void OnTimer1(object sender, EventArgs e) { if (seconds < 1) { PlaySound(@"Sound\2.wav", IntPtr.Zero, SND_ASYNC); btn_start.IsEnabled = false; btn_reset1.IsEnabled = true; btn_pause1.IsEnabled = false; combobox1.IsEnabled = true; combobox2.IsEnabled = true; combobox3.IsEnabled = true; return; } seconds--; label1.Content = TimerClass.GetTimeString1(seconds); } private void btn_start_Click(object sender, RoutedEventArgs e) { h = Convert.ToInt32(combobox1.Text); m = Convert.ToInt32(combobox2.Text); s = Convert.ToInt32(combobox3.Text); seconds = h * 3600 + m * 60 + s; label1.Content = TimerClass.GetTimeString1(seconds); timer1.Start(); btn_start.IsEnabled = false; btn_reset1.IsEnabled = true; btn_pause1.IsEnabled = true; combobox1.IsEnabled = false; combobox2.IsEnabled = false; combobox3.IsEnabled = false; } private void btn_reset_Click(object sender, RoutedEventArgs e) { seconds = 0; label1.Content = TimerClass.GetTimeString1(seconds); timer1.Stop(); btn_start.IsEnabled = true; btn_reset1.IsEnabled = false; btn_pause1.IsEnabled = false; combobox1.IsEnabled = true; combobox2.IsEnabled = true; combobox3.IsEnabled = true; } private void pause1_Click(object sender, RoutedEventArgs e) { if (btn_pause1.Content.ToString() == "暂停") { timer1.Stop(); btn_pause1.Content = "继续"; } else { timer1.Start(); btn_pause1.Content = "暂停"; } } int SEC = 0; private void OnTimer2(object sender, EventArgs e) { if (SEC < 1) { timer2.Stop(); playSound3(); btn_quick.IsEnabled = true; btn_cancel2.IsEnabled = false; combobox4.IsEnabled = true; return; } SEC--; label4.Content = TimerClass.GetTimeString1(SEC); } private void Button_Click(object sender, RoutedEventArgs e) { SEC = Convert.ToInt32(combobox4.Text) * 60; timer2.Start(); combobox4.IsEnabled = false; btn_quick.IsEnabled = false; btn_cancel2.IsEnabled = true; } private void Button_Click_1(object sender, RoutedEventArgs e) { SEC = 2; label4.Content = "00:00:00"; timer2.Stop(); combobox4.IsEnabled = true; btn_quick.IsEnabled = true; } IniFile INI = new IniFile(IniFile.AppIniName); public void LoadIni() { combobox1.Text = INI.ReadString("到计时", "时", "0"); combobox2.Text = INI.ReadString("到计时", "分", "0"); combobox4.Text = INI.ReadString("快速计时", "分", "0"); } public void SaveIni() { INI.WriteString("到计时", "时", combobox1.Text); INI.WriteString("到计时", "分", combobox2.Text); INI.WriteString("到计时", "秒", combobox3.Text); INI.WriteString("快速计时", "分", combobox4.Text); } } } using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Threading; using System.Windows.Threading; namespace StopWatch { /// /// WatchCtrl.xaml 的交互逻辑 /// public partial class WatchCtrl : UserControl { public WatchCtrl() { InitializeComponent(); timer1 = new DispatcherTimer(); timer1.Tick += new EventHandler(OnTimer1); timer1.Interval = new TimeSpan(0, 0, 1); timer1_1 = new DispatcherTimer(); timer1_1.Tick += new EventHandler(OnTimer1_1); timer1_1.Interval = new TimeSpan(0, 0, 0, 100); timer2 = new DispatcherTimer(); timer2.Tick += new EventHandler(OnTimer2); timer2.Interval = new TimeSpan(0, 0, 1); } private DispatcherTimer timer1 = null; private DispatcherTimer timer1_1 = null; private DispatcherTimer timer2 = null; private void OnTimer1(object sender, EventArgs e) { second++; label1.Content = TimerClass.GetTimeString1(second) ;//DateTime.Now.ToString("h:mm:ss"); } public int second = 0; private int second1 = 0; public int count = 0; private void OnTimer1_1(object sender, EventArgs e) { //label1.Content = TimerClass.GetTimeString1(second) + "." + count.ToString();//DateTime.Now.ToString("h:mm:ss"); //count++; //if (count > 9) // count = 0; } private void OnTimer2(object sender, EventArgs e) { second1++; label2.Content = TimerClass.GetTimeString1(second1) ;//.ToString("h:mm:ss"); } private void btn_start_Click(object sender, RoutedEventArgs e) { timer1.Start(); timer2.Start(); if (btn_start.Content.ToString() == "停止") { btn_start.Content = "开始"; btn_reset.Content = "复位"; timer1.Stop(); timer2.Stop(); } else { btn_start.Content = "停止"; btn_reset.Content = "计次"; } } private int counter = 0; private void btn_reset_Click(object sender, RoutedEventArgs e) { if (btn_reset.Content.ToString() == "复位") { second = 0; second1 = 0; label1.Content = "00:00:00"; label2.Content = "00:00:00"; timer1.Stop(); timer2.Stop(); } else { if (second1 > 0) { counter++; listbox1.Items.Add(string.Format(" {0}\t{1}", counter, label2.Content)); } second1 = 0; label2.Content = "00:00:00"; } if (btn_reset.Content.ToString() == "复位" && btn_start.Content.ToString()=="开始") { listbox1.Items.Clear(); } } } }
### 回答1: Android提供了CountDownTimer类可以用于倒计时,以下是一个简单的示例: 首先,在xml布局文件中添加一个TextView用于显示倒计时: ``` <TextView android:id="@+id/tv_countdown" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="24sp" android:textColor="@android:color/black" android:layout_centerInParent="true" /> ``` 然后,在Activity中实现CountDownTimer类,在onTick()方法中更新TextView的值,在onFinish()方法中处理倒计时结束的逻辑: ``` public class MainActivity extends AppCompatActivity { private TextView tvCountdown; private CountDownTimer countDownTimer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvCountdown = findViewById(R.id.tv_countdown); // 倒计时60秒,每秒更新一次 countDownTimer = new CountDownTimer(60 * 1000, 1000) { @Override public void onTick(long millisUntilFinished) { // 更新TextView的值 tvCountdown.setText(String.valueOf(millisUntilFinished / 1000)); } @Override public void onFinish() { // 处理倒计时结束的逻辑 tvCountdown.setText("倒计时结束"); } }.start(); // 开始倒计时 } @Override protected void onDestroy() { super.onDestroy(); // 取消倒计时 countDownTimer.cancel(); } } ``` 以上就是一个简单的倒计时控件实现。注意,在Activity销毁时要取消倒计时,避免内存泄漏。 ### 回答2: Android倒计时控件是一种用于实现倒计时功能的UI控件。它可以在界面上显示剩余时间,并根据设定的时间间隔更新显示内容,直到倒计时结束。 Android倒计时控件一般使用CountDownTimer类来实现。我们可以在页面上创建一个TextView用于显示倒计时的时间,然后创建一个CountDownTimer对象,并重写其onTick()和onFinish()方法来更新倒计时的显示。在onTick()方法中,我们可以通过计算剩余时间来更新TextView的内容,在onFinish()方法中,可以执行倒计时结束后的操作。 使用Android倒计时控件,我们可以方便地实现各种倒计时功能。例如,我们可以在游戏中使用它来显示回合剩余时间,或者在活动中使用它来显示活动倒计时。我们还可以根据不同的需求自定义倒计时的样式和显示内容,使其更符合我们的设计要求。 总的来说,Android倒计时控件是一种非常实用的UI控件,可以方便地实现倒计时功能,并且可以根据需要进行定制。无论是在游戏中还是在一些需要倒计时功能的应用场景中,它都能够为用户提供良好的体验和交互。 ### 回答3: Android倒计时控件是一种可以用于实现倒计时功能的控件倒计时是指从一个固定的时间开始,倒数到0的过程。在Android开发中,倒计时控件通常用于实现一些具有时效性的功能,比如短信验证码倒计时、限时抢购倒计时等。 Android提供了一些内置的倒计时控件,例如CountDownTimer。使用CountDownTimer控件可以很方便地实现倒计时功能。在使用CountDownTimer时,我们需要重写其onTick()方法和onFinish()方法,分别用来更新倒计时的显示和在倒计时结束时执行相应的操作。 除了内置的CountDownTimer外,也可以通过自定义控件来实现倒计时功能。自定义倒计时控件的实现方式较灵活,可以根据具体需求进行设计。通常,自定义倒计时控件需要继承自View或其子类,重写相关的方法来实现倒计时的逻辑。可以通过Handler、Timer或借助系统提供的计时器类来实现倒计时的功能。 总之,Android倒计时控件是一种用于实现倒计时功能的控件。通过内置的CountDownTimer或自定义控件的方式,可以在Android开发中很方便地使用倒计时功能,实现一些与时间有关的功能。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值