DFdou's Blog Life is short,Be yourself.

7kankan11bookekzwС˵Ҫ · uawx鶼Ķ ðƴӢ ޴½
3012/090

Android-ImageView setAlpha()的问题

不知道大家有没碰到这种情况,使用同一个图片资源做背景的ImageView,使用setAlpha之后,全部使用该图片资源的ImageView都会被影响到,导致这个问题的原因和解决方案如下:http://android-developers.blogspot.com/2009/05/drawable-mutations.html (PS:被和谐,需要爬墙。)
来个例子说明下,我们需要生成10个ImageView,偶数位的ImageView设置alpha,代码如下:

private int res_ico = R.drawable.icon;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    LinearLayout l= (LinearLayout)findViewById(R.id.layout1);
    for(int i=0;i < 10;i++){

        ImageView iv = new ImageView(this);
        iv.setImageResource(res_ico);
        iv.setClickable(false);

        iv.setAdjustViewBounds(true);
        if(i%2==0){
            ico.setAlpha(125);
        }
        l.addView(iv);
    }
}

这样的话就会发现,所有的ImageView的透明度是和最后设置的值一样的,具体原因在上边的网页里有说明,因为大家用的都是一个资源嘛。
那么怎么解决这个问题呢?
方案如下:

private int res_ico = R.drawable.icon;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    LinearLayout l= (LinearLayout)findViewById(R.id.layout1);
    for(int i=0;i < 10;i++){
        Drawable ico = getResources().getDrawable(res_ico);
        ImageView iv = new ImageView(this);
        iv.setBackgroundDrawable(ico);
        iv.setClickable(false);

        iv.setAdjustViewBounds(true);
        if(i%2==0){
            ico.mutate().setAlpha(125);
        }
        l.addView(iv);
    }
}

mutate()方法是让图片资源mutable,内部工作原理应该就是克隆了一份自己。
另外:

Drawable ico = getResources().getDrawable(res_ico);

要放在循环里,放在循环体外的话照样会出问题,囧。

Some Random Posts

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

:zhuang :xizao :wuwu :wenhao :wc :touxiang :shuaya :shuajian :shengtian :paopao :no :meinv :maonv :loveu :leilei :kua :jrjr :dahan :chi :chaocai :byebye


CommentLuv Enabled

No trackbacks yet.