下圖展示了不同View設置相同的圖片作爲背景時的實體關係圖,可以看出,兩個Drawable被創建,他們共享Constant State
code:
- public class Main extends Activity implements OnClickListener{
- /** Called when the activity is first created. */
- Button button;
- Button button2;
- TextView textView1;
- TextView textView2;
- Drawable icon;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- button = (Button)findViewById(R.id.button1);
- textView1 = (TextView)findViewById(R.id.textView1);
- textView2 = (TextView)findViewById(R.id.textView2);
- icon = getResources().getDrawable(R.drawable.icon);
- button.setOnClickListener(this);
- }
- @Override
- public void onClick(View v) {
- if (v.getId() == R.id.button1) {
- icon = getResources().getDrawable(R.drawable.icon);
- icon.setAlpha(50);
- textView1.setBackgroundDrawable(icon);
- icon = getResources().getDrawable(R.drawable.icon);
- icon.setAlpha(0);
- textView2.setBackgroundDrawable(icon);
- } else if (v.getId() == R.id.button2) {
- icon = getResources().getDrawable(R.drawable.icon);
- //icon.setAlpha(0);
- textView1.setBackgroundDrawable(icon);
- //icon.setAlpha(255);
- textView2.setBackgroundDrawable(icon);
- }
- }
- }
從運行效果可以看到,textView1和textView2的Alpha值都設置爲0,說明.setAlpha()方法改變了Drawable的Constant State
Android 1.5版本後,加入了mutate()方法,Drawable的Constant State不會發生變化,因爲mutate()方法返回Drawable的副本,修改屬性只修改Drawable副本的屬性。修改以上代碼:
- @Override
- public void onClick(View v) {
- if (v.getId() == R.id.button1) {
- icon = getResources().getDrawable(R.drawable.icon);
- icon.mutate().setAlpha(50);
- textView1.setBackgroundDrawable(icon);
- icon = getResources().getDrawable(R.drawable.icon);
- icon.mutate().setAlpha(0);
- textView2.setBackgroundDrawable(icon);
- }
- }
從運行結果來看,textView1和textView2有不同的透明度