您好,登錄后才能下訂單哦!
在自定義ImageView中處理圖片加載失敗可以通過(guò)重寫onDraw()
方法來(lái)實(shí)現(xiàn),例如:
public class MyImageView extends ImageView {
private Drawable mErrorDrawable;
public MyImageView(Context context) {
super(context);
}
public MyImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void setErrorDrawable(Drawable errorDrawable) {
mErrorDrawable = errorDrawable;
}
@Override
protected void onDraw(Canvas canvas) {
try {
super.onDraw(canvas);
} catch (Exception e) {
if (mErrorDrawable != null) {
mErrorDrawable.setBounds(0, 0, getWidth(), getHeight());
mErrorDrawable.draw(canvas);
}
}
}
}
在上面的代碼中,我們定義了一個(gè)MyImageView
類繼承自ImageView,并添加了一個(gè)mErrorDrawable屬性用于設(shè)置加載失敗時(shí)顯示的圖片。重寫了onDraw()
方法,在調(diào)用super.onDraw()時(shí)可能會(huì)拋出異常,我們捕獲異常后將mErrorDrawable繪制到Canvas上。這樣就能在圖片加載失敗時(shí)顯示自定義的圖片了。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。