我需要在10秒后隐藏TextView。我想我可以实现一个计时器,当经过的时间大于10000毫秒时,我隐藏了TextView。我的问题是计时器只能打一次然后停止。知道我错过了什么吗?
Activity ctx = this;
...
private void ShowText(String message)
{
txtProceed.setText(message);
txtProceed.setVisibility(View.VISIBLE);
chronoHideText = new Chronometer(ctx);
chronoHideText.setOnChronometerTickListener(new OnChronometerTickListener()
{
public void onChronometerTick(Chronometer arg0) {
long elapsed = SystemClock.elapsedRealtime() - chronoHideText.getBase();
Log.i("Chrono",String.valueOf(elapsed));
if (elapsedTime>10000)
{
txtProceed.setVisibility(View.INVISIBLE);
chronoHideText.stop();
}
}
}
);
chronoHideText.setBase(SystemClock.elapsedRealtime());
chronoHideText.start();
}
感谢Janusz的帮助。现在效果很好的解决方案是:
Handler splashHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
//remove SplashScreen from view
txtProceed.setVisibility(View.INVISIBLE);
break;
}
super.handleMessage(msg);
}
};
Message msg = new Message();
msg.what = 0;
splashHandler.sendMessageDelayed(msg, 10000);
答案 0 :(得分:4)
您可以使用发送延迟讯息的handler。 sendMessageDelayed方法使您能够指定时间,在此时间过后,您将收到消息。如果您只需要在经过一段时间后做一件事,就可以在handleMessage方法中隐藏视图。
这样您就不需要自己测量时间并且每秒或毫秒进行一次计算工作。在Android操作系统发送邮件之前,您的应用程序不会占用任何CPU时间。
答案 1 :(得分:1)
public class ButtonVisibility extends Activity {
Button mButton;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_button);
mButton = (Button)findViewById(R.id.button);
new MyTask().execute(null);
}
public class MyTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(10000);
}
catch(InterruptedException e) {
Log.e("MyTask", "InterruptedException", e);
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mButton.setVisibility(View.INVISIBLE);
}
}
}