2012年5月23日 星期三

[Android] ProxyView for XML Layout

    發Android的時候會盡量不破壞MVC的架構,所以對於Layout的定義能盡量寫xml就寫xml,但有時候還是會需要寫code的方式修改view的數值。 但如果想要擁有xml定義的好處,同時擁有動態更動數值的功能時,有一下幾種方式

一、放棄xml,完全用code去長View再addView

二、利用以下介紹proxy的方式

    以一個LinearLayout來說,裡面可能包含(1)TextView、(2)ImageView,而需要控制的程式邏輯變成 TextView.setText(String)以及ImageView.setImage(Bitmap)。

[test1.xml]

<> TODO </> 

    我們可以先把它定義成test1.xml,在src裡面建立一個ProxyView extends ViewGroup 當作中介容器。在constructor利用LayoutInflator.inflate(R.layout.test1)拿到該View並且this.addView(View)這樣xml裡面定義的view就加到自己的child。

[ProxyView]
context.getLayoutInflator().inflate(R.layout.test1,this);
this.textview = (TextView)context.findViewById(R.id.text1);
this.imageview = (ImageView)context.findViewById(R.id.image1);

    就可以在主程式加入這個ProxyView

[Activiy]
this.addView(new ProxyView(this));

    這時候要注意兩件事情:
    (1)ViewGroup default不會呼叫child的onDraw(),除非你呼叫 this.setWillNotDraw(false);
    (2)ViewGroup的onLayout必須正確實作,不然就是黑畫面
@Override protected void onLayout(boolean changed, int l, int t, int r, int b) {
        for(int i = 0 ; i < getChildCount() ; i++){
             getChildAt(i).layout(l, t, r, b); }
       }

參考資料: 

    http://stackoverflow.com/questions/4448779/how-to-inflate-xml-layout-file-correctly-inside-custom-viewgroup

沒有留言:

張貼留言