public class MainActivity extends AppCompatActivity {
ConstraintLayout cl;
int i;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cl=(ConstraintLayout)findViewById(R.id.cl);
cl.setBackgroundResource(R.drawable.bb1);
i=0;
new Timer().scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
cl.animate().alpha(0f).setDuration(1500);
if(i==0)
cl.setBackgroundResource(R.drawable.bb1);
else if(i==1)
cl.setBackgroundResource(R.drawable.bb2);
else if(i==2)
cl.setBackgroundResource(R.drawable.bb3);
else if(i==3)
cl.setBackgroundResource(R.drawable.bb4);
else if(i==4)
cl.setBackgroundResource(R.drawable.bb5);
else if(i==5)
cl.setBackgroundResource(R.drawable.bb6);
i++;
cl.animate().alpha(1f).setDuration(1500);
}
},0,3000);
}
}
错误:
E / AndroidRuntime:致命异常:Timer-0
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6902)
at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:1087)
at android.view.ViewGroup.invalidateChild(ViewGroup.java:5246)
at android.view.View.invalidateInternal(View.java:13573)
at android.view.View.invalidate(View.java:13509)
at android.view.View.invalidateDrawable(View.java:17693)
at android.graphics.drawable.Drawable.invalidateSelf(Drawable.java:432)
at android.graphics.drawable.Drawable.setVisible(Drawable.java:816)
at android.view.View.setBackgroundDrawable(View.java:18160)
at android.view.View.setBackground(View.java:18136)
at android.view.View.setBackgroundResource(View.java:18119)
at com.anilkrishna.baahubali2.MainActivity$1.run(MainActivity.java:30)
at java.util.TimerThread.mainLoop(Timer.java:555)
at java.util.TimerThread.run(Timer.java:505)
我的应用正在运行,第一张图片正在显示,正在淡出然后应用程序停止。问题在于if else循环。我无法搞清楚!
答案 0 :(得分:0)
在UI线程上执行timer内的代码,
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cl = (ConstraintLayout) findViewById(R.id.cl);
cl.setBackgroundResource(R.drawable.bb1);
i = 0;
new Timer().scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
cl.animate().alpha(0f).setDuration(1500);
if (i == 0)
cl.setBackgroundResource(R.drawable.bb1);
else if (i == 1)
cl.setBackgroundResource(R.drawable.bb2);
else if (i == 2)
cl.setBackgroundResource(R.drawable.bb3);
else if (i == 3)
cl.setBackgroundResource(R.drawable.bb4);
else if (i == 4)
cl.setBackgroundResource(R.drawable.bb5);
else if (i == 5)
cl.setBackgroundResource(R.drawable.bb6);
i++;
cl.animate().alpha(1f).setDuration(1500);
}
});
}
}, 0, 3000);
}