package name.cpr;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.util.Timer;
import java.util.TimerTask;
public class ExampleActivity extends ActionBarActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_example);
Timer timer = new Timer();
timer.schedule(new CheckConnection(), 0, 3000);
ImageView iv = (ImageView) findViewById(R.id.imageView);
iv.setVisibility(View.VISIBLE);
}
class CheckConnection extends TimerTask{
public void run(){
ImageView iv = (ImageView) findViewById(R.id.imageView);
iv.setVisibility(View.INVISIBLE); //<- Unfortunatly Error Here
}
}
}
启动应用程序,第一次图像视图可见性工作,但计时器不工作,如果计时器启动相同的错误,不幸的是....已经停止
答案 0 :(得分:0)
您可能想要使用android.os.Handler。
public class ExampleActivity extends ActionBarActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_example);
ImageView iv = (ImageView) findViewById(R.id.imageView);
iv.setVisibility(View.VISIBLE);
//
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
iv.setVisibility(View.INVISIBLE);
}
}, 3000);
}
}
祝你好运。 :)
答案 1 :(得分:0)
您正在做的是从非gui线程更新gui元素,该线程最终以RuntimeException
结尾。
解决此问题的一种方法是使用Handler
:
public class ExampleActivity extends Activity
{
private ImageView iv;
private ImgHandler handler;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_example);
this.iv = (ImageView) findViewById(R.id.imageView);
this.iv.setVisibility(View.VISIBLE);
this.handler = new ImgHandler(this.iv);
final Timer timer = new Timer();
timer.schedule(new CheckConnection(), 0, 3000);
}
/**
* The timer task to run every 3 seconds
*/
private final class CheckConnection extends TimerTask
{
public void run()
{
handler.sendEmptyMessage(0);
}
}
/**
* Custom <b>static</b> handler to bridge between the timer task's thread and the gui
*/
private static final class ImgHandler extends Handler
{
// use a weak reference to the ImageView instance you'd like to manipulate:
private final WeakReference<ImageView> imageReference;
public ImgHandler(final ImageView img)
{
this.imageReference = new WeakReference<ImageView>(img);
}
@Override
public void handleMessage(Message msg)
{
if (imageReference == null)
return; // no image to show / hide
final ImageView img = imageReference.get();
// since this is the single message we are handling, no switch is used:
if (img != null)
{
img.setVisibility(img.getVisibility() == View.VISIBLE ? View.INVISIBLE : View.VISIBLE);
}
}
}
}
上面的示例将每隔3秒更改一次imageView的可见性,但您的示例中并不清楚这是否是您的意图。