2012-02-03 71 views
1

目前我的源代码看起来像这样如何在运行时让TextView更改文本?

System.out.println(text1+" "+text2); // displays the correct values. 

    this.view1.setText(""+text1); // should display the same values 
    this.view1.setText(""+text2); // 

    ((Activity)getContext()).runOnUiThread(new Runnable() 
    { 
     public void run() 
     { invalidate(); } 
    }); 

这是一家由每30秒另一个对象调用方法的一部分。 TextViews放置在LinearLayout上。

开始显示的文字是“0”。 现在我希望它每隔30秒更改一次以显示给定的文本(例如“5”和“10”)。

看来,意见不重画。

我希望能够说清楚。谢谢!

+0

用最后一个setText()方法查看您正在重写text1的示例 – 2012-02-03 08:37:28

+0

您是否在UI线程中设置了文本? – 2012-02-03 08:47:17

+0

不能理解你的问题..我的意思就像一个计时器..然后你可以使用计时器来实现这个 – 2012-02-03 08:50:37

回答

0

也许您的错误取决于“text1”和“text2”的错误对象类型。 这个变量都是String对象还是Integer?如果使用整型(INT),你需要 的变量值转换为字符串:

String str1 = String.valueOf(text1); 
this.view1.setText(str1); 

String str2 = String.valueOf(text2); 
this.view2.setText(str2); 
0

设置文本不应该要求你无效的TextView去改变它。

你是肯定你想这样做吗?

this.view1.setText(""+text1); // should display the same values 
this.view1.setText(""+text2); // 
0

实际上,Context类没有一个runOnUiThread方法,所以你需要一个Activity对象执行此方法。并且您必须在runOnUiThread方法内调用textView.setText方法才能使其正常工作。希望这可以帮助。

0

你可以使用处理程序来更新textview的值。

调用具有值的处理程序。

Message m = new Message(); 
    m.what = -1; 
    m.arg1 = remainTime; 
handler.sendMessage(m); 
******* Handler*****          
     public static Handler handler = new Handler() { 
       public void handleMessage(Message msg) { 

        if (msg.what == -1) { 

         set_timer(msg.arg1); 

        } 
     } 
     }; 


     *********Updating Text*************** 

     public static void set_timer(int time) { 

       if (time == 0) { 

        Toast.makeText(context, "Time Out...", Toast.LENGTH_SHORT).show(); 
        System.exit(0); 

       } else { 
        if (sec < 10) 
         timeindex.setText(time + " : 0" + sec + " of " + value[0]); 
        else 
         timeindex.setText(time + " : " + sec + " of " + value[0]); 
       } 

      } 

希望ü得到它....

0

真正的类看起来比较复杂,但这个例子显示了我的(工作)的答案,并应明确它如何工作。

public class MyObject extends LinearLayout<br /> 
{ 

    private TextView text1,text2; 
    private String str_text1, str_text2; 

    /* The constructor does the initialisation of all fields ... */ 
    public MyObject(Context context) 
    { /* Initialisation ... */ } 

    /*This method is called from outside by a thread to renew the displayed values.*/ 
    public final void method_A() 
    { 
     ((Activity)getContext()).runonUIThread(
     new Runnable() 
     { 
       public void run() 
       { 
        text1.setText(str_text1); 
        text2.setText(str_text2); 
       } 
     }); 
    } 
    /* This method is called from outside by an object to initialize the two values */ 
    method_B(String str_text1, String str_text2) 
    { 
     this.str_text1 = str_text1; 
     this.str_text2 = str_text2; 
    } 
}