java - 使用时钟更新 TextView

标签 java android timer textview clock

我一直在尝试创建一个程序,该程序将输出一个工作数字时钟,使我能够快速访问日期和时间。我有解析时间的代码,但是,我在更新 TextView 时遇到困难。我有这个:

    `public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    timer = (TextView)findViewById(R.id.timer);

    time = new Time();
    time.setToNow();

    timeString = time.toString();
    changeTime = Parser(timeString);


    time.setToNow();
    timeString = time.toString();
    changeTime = Parser(timeString);

    timer.setText(changeTime);  
    } 
    private String Parser(String time){

    String year = time.substring(0, 4);
    String month = time.substring(4,6);
    String day = time.substring(6, 8);
    String hour = time.substring(9,11);
    String minute = time.substring(11, 13);
    String second = time.substring(13, 15);

    String finalTime = hour + ":" + minute + ":" + second + " " + day + " " + month + " "  + year;
    //String finalTime = second;
    return finalTime;


}`

如何将其放入循环中以不断更新 TextView 。

感谢您给我的任何帮助。

最佳答案

用永无休止的处理程序消息来开始更新 View 是一种不好的做法(尝试查看进程的 CPU 级别)。 更好、更优雅的方法是注册一个将触发更新的 BroadcastReceiver

public class Clock extends LinearLayout {

    private Calendar mCalendar;
    private LinearLayout mLayoutTime;
    private TextView mAMPMText;
    private TextView mDateText;
    private TextView mTimeText;
    private View mSendFeedback;
    private boolean mAttached;

    private final Handler mHandler = new Handler();
    SimpleDateFormat dateFormatter = new SimpleDateFormat("EEE, MMM d, yyyy");
    SimpleDateFormat timeFormatter = new SimpleDateFormat("h:mm");

    public Clock(final Context context, int layoutResourceID, int dateResId, int meResId,int amPmResId) {
        super(context);
        LayoutInflater layoutInflater = LayoutInflater.from(context);
        View view = layoutInflater.inflate(layoutResourceID, null);
        addView(view, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        mAMPMText = (TextView) view.findViewById(amPmResId);
        mTimeText = (TextView) view.findViewById(timeResId);
        mDateText = (TextView) view.findViewById(dateResId);    
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();

        if (!mAttached) {
            mAttached = true;
            IntentFilter filter = new IntentFilter();

            filter.addAction(Intent.ACTION_TIME_TICK);
            filter.addAction(Intent.ACTION_TIME_CHANGED);
            filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);

            getContext().registerReceiver(mIntentReceiver, filter, null, mHandler);
        }

        // NOTE: It's safe to do these after registering the receiver since the receiver always runs
        // in the main thread, therefore the receiver can't run before this method returns.

        // The time zone may have changed while the receiver wasn't registered, so update the Time
        mCalendar = Calendar.getInstance();

        // Make sure we update to the current time
        onTimeChanged();
        updateView();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (mAttached) {
            getContext().unregisterReceiver(mIntentReceiver);
            mAttached = false;
        }
    }

    private void updateView(){
        mTimeText.setText(timeFormatter.format(mCalendar.getTime()));
        mDateText.setText(dateFormatter.format(mCalendar.getTime()));
        mAMPMText.setText(mCalendar.get(Calendar.AM_PM) == 0 ? "AM" : "PM");
    }

    private void onTimeChanged() {
        mCalendar.setTime(new Date());

        updateContentDescription(mCalendar);
    }

    private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_TIMEZONE_CHANGED)) {
                String tz = intent.getStringExtra("time-zone");
                mCalendar.setTimeZone(TimeZone.getTimeZone(tz));
            }

            onTimeChanged();

            updateView();
        }
    };

    private void updateContentDescription(Calendar calendar) {
        setContentDescription(calendar.toString());
    }
}

布局(可以做得更好)

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:gravity="center_vertical"
    android:orientation="horizontal" >

    <LinearLayout
        android:id="@+id/layout_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/time_txt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:includeFontPadding="true" />

        <TextView
            android:id="@+id/am_pm_txt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="AM" />
    </LinearLayout>

    <TextView
        android:id="@+id/date_txt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</RelativeLayout>

关于java - 使用时钟更新 TextView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16153971/

相关文章:

java - 从对象中删除 HashMap 键

java - 检查 Firebase 实时数据库中的值是否等于字符串

java - 当问题没有适当的解决方案时,有什么建议?

android - Intent.ACTION_USER_PRESENT 未在 HoneyComb 或 ICS(三星)设备上收到

swift - 如何将 UItapGesture 识别器指定为按钮的 CGpoint

Java 从 JavaEE 应用程序中的不同 SMTP 服务器发送电子邮件

android - 在运行时更改自定义键盘中按键的图标

java - Android 上的 ARCore 是否支持像 ARKit 一样的实时反射?

c - 为什么这没有在正确的时间中断?

java - Swing 计时器——时间波动