我希望一旦按下菜单中的按钮, TextView 中的文本就会不断变化。这是我的菜单的 onOptionsItemSelected:
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.menu_animate:
for(int i=0;i<100;i++){
MessageIn.setText("here"+i);
}
break;
}
return super.onOptionsItemSelected(item);
}
正如您所看到的,如果 onOptionsItemSelected 认为在菜单中按下了“menu_animate”按钮,它会继续修改我的 TextView 中名为“MessageIn”的文本。
我试图让它重复显示一些数字从 0 到 99 的文本。但是,当我运行应用程序并按下按钮时,我只看到“here99”显示在我的 TextView 中。所以看起来所有代码都是在显示最终结果之前执行的。
如何让它在每次更新数字 i 时刷新 TextView 中的显示?
Thanks.
您可以使用Handler
and a Runnable
为了您的目的。我正在分享一个编辑过的代码,我目前使用的代码就像您的目的一样。
你可以直接复制类和布局,然后尝试一下。
主要思想是使用Handler
以其post
and postDelayed
方法与Runnable
。当您按下按钮时,它开始每 3 秒更改一次文本。如果您再次按下按钮,它会自行重置。
尝试这段代码,尝试理解它。Handler
s 可用于多种目的来更改 UI。阅读更多相关内容。
MainActivity.java:
public class MainActivity extends Activity {
private Handler handler;
private TextView textView;
private TextUpdateRunnable textUpdateRunnable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler();
textView = (TextView)findViewById(R.id.textView);
Button startButton = (Button)findViewById(R.id.button);
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(textUpdateRunnable != null) {
handler.removeCallbacks(textUpdateRunnable);
}
TextUpdateRunnable newTextUpdateRunnable = new TextUpdateRunnable(handler, textView);
textUpdateRunnable = newTextUpdateRunnable;
handler.post(textUpdateRunnable);
}
});
}
private static class TextUpdateRunnable implements Runnable {
private static final int LIMIT = 5;
private int count = 0;
private Handler handler;
private TextView textView;
public TextUpdateRunnable(Handler handler, TextView textView) {
this.handler = handler;
this.textView = textView;
}
public void run() {
if(textView != null) {
textView.setText("here" + count);
count++;
if(handler != null && count < LIMIT) {
handler.postDelayed(this, 3000);
}
}
}
};
}
活动_main.xml:
<LinearLayout 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"
android:orientation="vertical" >
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="BUTTON" />
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)