StateListDrawable cannot be cast to android.graphics.drawable.GradientDrawab

項目裏面最近很多客戶端自定義的按鈕形狀跟底色要從服務器返回,今天測試遇到一問題,記錄一下下:

錯誤的寫法:

 GradientDrawable gradientDrawable = ((GradientDrawable)((TextView)helper.getView(R.id.tv_subject)).getBackground());
if(null !=item.bcolor && !TextUtils.isEmpty(item.bcolor)){
    int color = Color.parseColor(item.bcolor);
    gradientDrawable.setStroke(1,color);
    gradientDrawable.setColor(color);
}

正確寫法:

StateListDrawable background = (StateListDrawable) ((TextView)helper.getView(R.id.tv_subject)).getBackground();
Drawable current = background.getCurrent();
if(current instanceof GradientDrawable){
    GradientDrawable gradientDrawable= (GradientDrawable) current;
    if(null !=item.bcolor && !TextUtils.isEmpty(item.bcolor)){
        int color = Color.parseColor(item.bcolor);
        gradientDrawable.setStroke(1,color);
        gradientDrawable.setColor(color);
    }
}

雖然還是不明白爲什麼要這麼做,但是不這麼做測試還是不行。。。。

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