用Handler更新一個TextView的背景顏色在5種顏色中循環變換
Handle特點:
1,傳遞Message。用於接收子線程發送的數據,並用此數據配合主線程更新UI。
2,傳遞Runable對象。用於通過Handler綁定的消息隊列,安排不同操作的執行順序。
第一種實現方法:
import java.util.Random; import com.example.handle.R.color; import android.R.integer; import android.app.Activity; import android.content.res.Resources.Theme; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.widget.TextView; public class MainActivity extends Activity { TextView tv; int color[]; Handler myHandler; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv=(TextView)findViewById(R.id.tv); color=new int[]{ R.color.black, R.color.blue, R.color.red, R.color.yellow, R.color.green };//背景顏色數組 myHandler=new Handler(); myHandler.post(rb); } Runnable rb=new Runnable(){ public void run(){ Random rd=new Random();//產生隨機數 int i=rd.nextInt(5); tv.setBackgroundColor(getResources().getColor(color[i])); myHandler.postDelayed(rb,1000);//設置延遲時間 } }; }
import android.app.Activity; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.os.Message; public class SecondActivity extends Activity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); new updateColor().start(); } Handler handler=new Handler(){ public void handleMessage(Message msg){ Resources res = getResources(); Drawable drawable = res.getDrawable(R.color.black); Drawable drawable1 = res.getDrawable(R.color.aqua); Drawable drawable2 = res.getDrawable(R.color.green); Drawable drawable3 = res.getDrawable(R.color.red); Drawable drawable4 = res.getDrawable(R.color.pink); Bundle b=msg.getData(); int key=b.getInt("key"); switch(key){ case 0: SecondActivity.this.getWindow().setBackgroundDrawable(drawable) ; break; case 1:SecondActivity.this.getWindow().setBackgroundDrawable(drawable1); break; case 2:SecondActivity.this.getWindow().setBackgroundDrawable(drawable2); break; case 3:SecondActivity.this.getWindow().setBackgroundDrawable(drawable3); break; case 4:SecondActivity.this.getWindow().setBackgroundDrawable(drawable4); break; } } }; class updateColor extends Thread{ int i=0; public void run() { while(true){ Message msg=handler.obtainMessage(); Bundle bundle=new Bundle(); if(i<5){ try { bundle.putInt("key", i); msg.setData(bundle); i=i+1; handler.sendMessage(msg); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } }else{ i=i%5; } } } } }