我写了一个小应用程序,它每 3 秒更改一次应用程序背景。我使用 Handler 和 Runnable 对象来实现这一点。它工作正常。这是我的代码:
public class MainActivity extends Activity {
private RelativeLayout backgroundLayout;
private int count;
private Handler hand = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button clickMe = (Button) findViewById(R.id.btn);
backgroundLayout = (RelativeLayout) findViewById(R.id.background);
clickMe.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
count = 0;
hand.postDelayed(changeBGThread, 3000);
}
});
}
private Runnable changeBGThread = new Runnable() {
@Override
public void run() {
if(count == 3){
count = 0;
}
switch (count) {
case 0:
backgroundLayout.setBackgroundColor(getResources().getColor(android.R.color.black));
count++;
break;
case 1:
backgroundLayout.setBackgroundColor(Color.RED);
count++;
break;
case 2:
backgroundLayout.setBackgroundColor(Color.BLUE);
count++;
break;
default:
break;
}
hand.postDelayed(changeBGThread, 3000);
}
};
}
在这里,我在非 UI 线程中更改 UI 背景,即backgroundLayout.setBackgroundColor(Color.RED);
在 run(); 它是如何工作的?