2011-04-26 62 views
4

我有一個自定義視圖,我想從資源模板創建。我的自定義視圖構造函數接受額外的參數,這些參數被設置爲自定義視圖的附加信息。Android使用現有視圖對象充氣視圖

問題是當我膨脹視圖我得到的視圖對象不是從自定義視圖的子類,因爲膨脹方法是靜態的,並返回一個通用的新視圖,而不是我的自定義視圖的實例。

我在尋找的是一種通過將自定義視圖對象引用傳遞給視圖來誇大視圖的方法。

 
public class MLBalloonOverlayView extends View { 
    MiscInfo mMiscInfo; 
    public MLBalloonOverlayView(Context context, MiscInfo miscInfo) { 
     super(context); 
     mMiscInfo = miscInfo; 
    } 
    public View create(final int resource, final OverlayItem item, 
         MapView mapView, final int markerID) { 
     ViewGroup viewGroup = null; 
     View balloon = View.inflate(getContext(), resource, viewGroup); 

     // I want to return this object so later I can use its mMiscInfo 
     //return this; 
     return balloon; 
    } 
} 

回答

1

https://github.com/galex/android-mapviewballoons 查看代碼後,我能夠相應地更新我的代碼。這個想法是你從資源創建一個佈局,然後你將這個膨脹的視圖添加到擴展布局的類的實例中(如上面的Marcos所建議的那樣)。

public class MLBalloonOverlayView extends FrameLayout { 

    public MLBalloonOverlayView(Context context, final OverlayItem overlayItem) { 
     super(context); 
     mOverlayItem = overlayItem; 
    } 

    public void create(final int resource, MapView mapView, final int markerID) { 
     // inflate resource into this object 
     TableLayout layout = new TableLayout(getContext()); 
     LayoutInflater.from(getContext()).inflate(resource, layout); 
     TableLayout.LayoutParams params = new TableLayout.LayoutParams(
       LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
     params.gravity = Gravity.NO_GRAVITY; 
     this.addView(layout, params); 
    } 
} 
1

將它膨脹在你的物體上。

public View create(final int resource, final OverlayItem item, 
        MapView mapView, final int markerID) { 
    LayoutInflater.from(getContext()).inflate(resource, this, true); 
    return this; 
} 
+0

不幸的是,這個附加的新充氣視圖「這個」作爲一個ViewGroup中,而不是作爲一個視圖和我預期的目的,我需要一個視圖,而不是一個ViewGroup(我作爲添加視圖到地圖自定義氣球視圖)。 – faridz 2011-04-27 14:36:36

+0

如果您的視圖是組合式佈局,則應該使用擴展布局的東西,而不僅僅是視圖。 – 2011-04-27 15:00:53