Drawable Mutations

下圖展示了不同View設置相同的圖片作爲背景時的實體關係圖,可以看出,兩個Drawable被創建,他們共享Constant State

code:

  1. public class Main extends Activity implements OnClickListener{  
  2.     /** Called when the activity is first created. */  
  3.       
  4.     Button button;  
  5.     Button button2;  
  6.     TextView textView1;  
  7.     TextView textView2;  
  8.     Drawable icon;  
  9.     @Override  
  10.     public void onCreate(Bundle savedInstanceState) {  
  11.         super.onCreate(savedInstanceState);  
  12.         setContentView(R.layout.main);  
  13.         button = (Button)findViewById(R.id.button1);  

 

  1.         textView1 = (TextView)findViewById(R.id.textView1);  
  2.         textView2 = (TextView)findViewById(R.id.textView2);  
  3.         icon = getResources().getDrawable(R.drawable.icon);  
  4.          
  5.         button.setOnClickListener(this);  
  6.      
  7.     }  
  8.     @Override  
  9.     public void onClick(View v) {  
  10.         if (v.getId() == R.id.button1) {  
  11.             icon = getResources().getDrawable(R.drawable.icon);  
  12.             icon.setAlpha(50);  
  13.             textView1.setBackgroundDrawable(icon);  
  14.             icon = getResources().getDrawable(R.drawable.icon);  
  15.             icon.setAlpha(0);  
  16.             textView2.setBackgroundDrawable(icon);  
  17.         } else if (v.getId() == R.id.button2) {  
  18.                 icon = getResources().getDrawable(R.drawable.icon);  
  19.                 //icon.setAlpha(0);  
  20.                 textView1.setBackgroundDrawable(icon);  
  21.                 //icon.setAlpha(255);  
  22.                 textView2.setBackgroundDrawable(icon);  
  23.         }  
  24.     }  

從運行效果可以看到,textView1和textView2的Alpha值都設置爲0,說明.setAlpha()方法改變了Drawable的Constant State

Android 1.5版本後,加入了mutate()方法,Drawable的Constant State不會發生變化,因爲mutate()方法返回Drawable的副本,修改屬性只修改Drawable副本的屬性。修改以上代碼:

  1. @Override  
  2.     public void onClick(View v) {  
  3.         if (v.getId() == R.id.button1) {  
  4.              icon = getResources().getDrawable(R.drawable.icon);  
  5.             icon.mutate().setAlpha(50);  
  6.             textView1.setBackgroundDrawable(icon);  
  7.             icon = getResources().getDrawable(R.drawable.icon);  
  8.             icon.mutate().setAlpha(0);  
  9.             textView2.setBackgroundDrawable(icon);  
  10.         }   
  11.     } 

從運行結果來看,textView1和textView2有不同的透明度

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章