android - TextView.setText()使我的应用程序崩溃

标签 android crash textview

我正在学习Android,并且已经在使用完整的基础知识时遇到了麻烦:

我想有一个递增TextView的计时器,但在计时器第一次计时时它崩溃。

这是我的代码:

public class Game extends Activity {

Timer timer = new Timer();
int i = 0;
TextView text;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_game);

    text = (TextView) findViewById(R.id.timerText); 
    text.setText("0");

    timer.schedule(new TimerTask() {
        public void run() {
            i++;
            System.out.println(i);
            text.setText(i + "");
            if(i>100) timer.cancel();
        }
    }, 1000, 1000);
}
}

这是我的XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

...

<TextView
    android:id="@+id/timerText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="50dp"
    android:text="Large Text"
    android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>

我发现了很多解决setText崩溃的方法,但是似乎都没有解决方案。

最佳答案

您需要从text.setText(i + "");调用runOnUiThread()

关于android - TextView.setText()使我的应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24109827/

相关文章:

android - 谷歌眼镜 setText() 不工作

android - Flutter:app/build 文件夹和文件是否应该包含在 git 忽略中?

android - android中的布局问题

Android 谷歌地图无法在 fragment 中工作

android - 我的 androids 应用在某些设备上存在基于 Activitynotfoundexception 的崩溃。我怎样才能再生它?

C# WinForms 崩溃,没有异常

android - 您好Android Sudoku游戏,按下按钮会使游戏崩溃

android - 如何使用按钮在 TextView 中设置文本并更改屏幕?

java - 如何做偏好属性android :dependency?的相反

Android ActionBar 兼容性 : MenuItem. setActionView(View)