【问题标题】:TextSwitcher not updatingTextSwitcher 没有更新
【发布时间】:2011-03-09 18:50:20
【问题描述】:

所以我有一个 TextSwitcher,我想用它自活动打开以来的秒数每秒更新一次。这是我的代码

公共类 SecondActivity 扩展 Activity 实现 ViewFactory
{
    私有 TextSwitcher 计数器;
    私人计时器秒计数器;
    int elapsedTime = 0;

    @覆盖
    public void onCreate(Bundle savedInstanceState)
    {
        // 创建布局
        super.onCreate(savedInstanceState);

        setContentView(R.layout.event);

        // 记录经过时间的计时器
        计数器 = (TextSwitcher) findViewById(R.id.timeswitcher);
        中的动画 = AnimationUtils.loadAnimation(this,
                android.R.anim.fade_in);
        动画输出 = AnimationUtils.loadAnimation(this,
                android.R.anim.fade_out);
        counter.setFactory(this);
        counter.setInAnimation(in);
        counter.setOutAnimation(out);

        secondCounter = new Timer();
        secondCounter.schedule(new TimerUpdate(), 0, 1000);
    }

    /**
     * 每秒更新时钟计时器
     */
    公共无效更新时钟()
    {
        //更新时间
        经过时间++;
        int hours = elapsedTime/360;
        int 分钟 = elapsedTime/60;
        int 秒 = elapsedTime%60;

        // 根据小时数、分钟数和秒数格式化字符串
        字符串时间 = "";

        如果(!小时> = 10)
        {
            时间+=“0”;
        }
        时间 += 小时 + ":";

        如果(!分钟> = 10)
        {
            时间+=“0”;
        }
        时间 += 分钟 + ":";

        如果(!秒> = 10)
        {
            时间+=“0”;
        }
        时间+=秒;

        // 将文本设置为 textview
        counter.setText(时间);
    }

    私有类 TimerUpdate 扩展 TimerTask
    {
        @覆盖
        公共无效运行()
        {
            更新时钟();
        }
    }

    @覆盖
    公共视图 makeView()
    {
        Log.d("MakeView");
        TextView t = new TextView(this);
        t.setTextSize(40);
        返回 t;
    }
}

所以基本上,我有一个计时器,每秒钟增加一秒钟,它们格式化我想要显示的方式并设置 TextSwitcher 的文本,我认为它称为 makeView,但 makeView 只被调用一次并且时间保持不变如 00:00:01。我是否错过了一步,我认为这个 UI 对象没有很好的文档记录。

谢谢,杰克

【问题讨论】:

    标签: android


    【解决方案1】:

    您只能在 UI 线程中更新 UI。所以在你的例子中你可以做这样的事情。

    private Handler mHandler = new Handler() {
         void handleMessage(Message msg) {
              switch(msg.what) {
                   CASE UPDATE_TIME:
                        // set text to whatever, value can be put in the Message
              }
         }
    }
    

    然后调用

    mHandler.sendMessage(msg);
    

    在 TimerTask 的 run() 方法中。

    这是您当前问题的解决方案,但可能有更好的方法可以在不使用 TimerTasks 的情况下做到这一点。

    【讨论】:

    • 我以前从未使用过处理程序。那么我可以在那个 switch 语句中调用 updateClock 吗?
    • 而且我不明白为什么 makeView 会被调用一次,然后不再调用。我觉得这个解决方案已经足够复杂了。
    • 这实际上是您正在尝试做的一个示例。 developer.android.com/resources/articles/timed-ui-updates.html
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多