2014-05-01 41 views
1

我試圖更新一個EditText視圖,使得最終結果類似於像這樣的背景下邊界...更新背景界定

+----------------+ 
| Empty Space | 
|    | 
| +------------+ | 
| | Background | | 
| +------------+ | 
+----------------+ 

我目前的做法是爲了獲得onLayout和簡單的背景更新邊界...

@Override 
protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 
    super.onLayout(changed, left, top, right, bottom); 
    ... 
    getBackground().setBounds(newLeft, newTop, newRight, newBottom); 
} 

但是,這根本不起作用。邊界正在被應用,但是當它被繪製時,它不會改變。最接近的我來了,正在改變onDraw的界限,但是,它最初將被繪製在它的原始位置,然後立即被重新繪製到它的新位置......我如何可靠地改變背景界限?

回答

1

一些研究之後,我能解決這個問題的唯一辦法,就是創建一箇中介繪製對象(中間人),並委派所有公共方法實際可繪製。然後覆蓋setBounds設置我想要的任何值...

public class MyCustomView extends EditText { 

    @Override 
    public void setBackground(Drawable background) { 
    super.setBackground(new IntermediaryDrawable(background)); 
    } 

    ... 

    private class IntermediaryDrawable extends Drawable { 
    private Drawable theRealDrawable; 

    public IntermediaryDrawable(Drawable source) { 
     theRealDrawable = source; 
    } 

    @Override 
    public void setBounds(int left, int top, int right, int bottom) { 
     theRealDrawable.setBounds(left, 100, right, bottom); 
    } 

    ... 
    } 
} 

漂亮哈克。如果任何人遇到這個更好的解決方案,請分享。

+0

另一種方法是從'View'類重寫'draw(Canvas canvas)'方法,並在繪製背景之前設置邊界,IMO也很糟糕。你的方法可能是做到這一點的最好方法。 – Writwick