![](/img/trans.png)
[英]APP Widget Textview not updating (Java, android studio)
[英]Wrong updating TextView in Android app
我使用最新的Android Studio创建了一个简单的Android应用( https://www.linux.com/learn/docs/683628-android-programming-for-beginners-part-1 )。 码:
public class test_act extends Activity {
private static final int MILLIS_PER_SECOND = 1000;
private static final int SECONDS_TO_COUNTDOWN = 30;
private android.widget.TextView countdownDisplay;
private android.os.CountDownTimer timer;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.full_act);
countdownDisplay = (android.widget.TextView) findViewById(R.id.time_display_box);
android.widget.Button startButton = (android.widget.Button) findViewById(R.id.startbutton);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
try {
showTimer(SECONDS_TO_COUNTDOWN * MILLIS_PER_SECOND);
} catch (NumberFormatException e) {
// method ignores invalid (non-integer) input and waits
// for something it can use
}
}
});
}
private void showTimer(int countdownMillis) {
if(timer != null) { timer.cancel(); }
timer = new android.os.CountDownTimer(countdownMillis, MILLIS_PER_SECOND) {
@Override
public void onTick(long millisUntilFinished) {
countdownDisplay.setText("counting down: " +
millisUntilFinished / MILLIS_PER_SECOND);
}
@Override
public void onFinish() {
countdownDisplay.setText("KABOOM!");
}
}.start();
}
}
我的XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/time_display_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="60dp"
android:text="@string/_00_30"
android:textAppearance="?android:attr/textAppearanceLarge"/>
<Button
android:id="@+id/startbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/time_display_box"
android:layout_centerHorizontal="true"
android:layout_marginTop="41dp"
android:text="@string/start" />
</RelativeLayout>
在模拟器中,这是很好的工作。 但是在我使用CyanogenMod10.1(Android 4.2.2)应用程序的Galaxy S2上,错误地更新了TextView。 屏幕截图:
我该如何解决这个问题?
upd:屏幕旋转后,TextView更新一次。
您可能想在每次更新布局时尝试使布局无效。 我猜测文本更新的频率是多少,电话没有足够的时间重新绘制布局。 这也可以解释为什么在旋转手机时它可以工作,因为这样会强制更新布局。
countdownDisplay.invalidate();
让我知道那是否行不通。
当您将UI更新放在try
块中,尝试避免它或使用runOnUiThread包装时,通常会发生这种情况。
编辑:
另一个原因-您更新得很快-您的代码每秒执行1000次更新,我认为它无法处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.