我正在学习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/