【问题标题】:passing and setting TextView from another class从另一个类传递和设置 TextView
【发布时间】:2014-05-10 13:12:49
【问题描述】:

我的 android 活动中有一个文本视图,我想将它传递给另一个 java 类中的函数并修改它的文本。但这给了我一个例外。我读到我需要在 UI 线程上运行它或发送到上下文变量,但我有点困惑,我无法做到。这是我的代码:

Java 定时器类

public class CountdownTimer {
static int duration;
static Timer timer;

public static void startTimer(final TextView TVtime) {
    duration = 10;

    timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {

        public void run() {
            TVtime.setText(setDuration());
        }
    }, 1000, 1000);
}

private static String setDuration(){
    if(duration == 1)
        timer.cancel();
    return String.valueOf(--duration);
}
}

Android 活动:

TVtime = (TextView) findViewById(R.id.textView_displayTime);
CountdownTimer.startTimer(TVtime);

【问题讨论】:

    标签: java android textview


    【解决方案1】:

    您无法从非 UI 线程更新 UI。将activity Context 传递给startTimer() 方法。

    public static void startTimer(final TextView TVtime,final Context activityContext) {
        duration = 10;
    
        timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
    
           public void run() {
              ((Activity) activityContext).runOnUiThread(new Runnable() {
                    public void run()
                    {
                         TVtime.setText(setDuration());
                    }
                });
    ..........................
    .......................
    

    Android 活动:

    TVtime = (TextView) findViewById(R.id.textView_displayTime);
    CountdownTimer.startTimer(TVtime, YourActivity.this);
    

    【讨论】:

    • 由于某种原因它说activityContext没有runOnUiThread方法
    • 忘了说。您必须将其转换为 Activity。查看更新的答案。
    • 我没有尝试过,但无论如何感谢,我使用了处理程序解决方案。您知道其中一种相对于另一种的优点\缺点吗?
    • 参考这个 SO 问题:stackoverflow.com/questions/12618038/… 使用 runOnUiThread 确保您的代码将在 UI 线程中运行。
    【解决方案2】:

    您可以为此使用android.os.Handler

    public static void startTimer(final TextView TVtime) {
        duration = 10;
    
        final Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                TVtime.setText((String) msg.obj);
            }
        };
    
        timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
    
            public void run() {
                Message msg = new Message();
                msg.obj = setDuration();
                handler.sendMessage(msg);
            }
        }, 1000, 1000);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多