4

I have a custom view that I would like to create from a resource template. My custom view constructor accepts additional parameters that are set as additional info for the custom view.

Problem is when I inflate the view I get a view object that is not subclassed from from custom view since the inflate method is static and returns a generic new view instead of an instance of my custom view.

Would I am looking for is a way to inflate the view by passing it my custom view object reference.

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;
    }
}
faridz
  • 729
  • 1
  • 9
  • 9

2 Answers2

2

After looking at code at https://github.com/galex/android-mapviewballoons I was able to update my code accordingly. The idea being you create a layout from the resource and then you add the inflated view to the instance of a class that extends a layout (as Marcos suggested above).

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);
    }
}
smac89
  • 39,374
  • 15
  • 132
  • 179
faridz
  • 729
  • 1
  • 9
  • 9
1

Inflate it on your object.

public View create(final int resource, final OverlayItem item, 
                    MapView mapView, final int markerID) {
  LayoutInflater.from(getContext()).inflate(resource, this, true);
  return this;
}
Marcos Vasconcelos
  • 18,136
  • 30
  • 106
  • 167
  • Unfortunately, this attaches the newly inflated view to 'this' as a ViewGroup rather than as a View and for my intended purpose I need a View and not a ViewGroup (I am adding the view to a map as a custom balloon view). – faridz Apr 27 '11 at 14:36
  • If your view is a composed layout, you should work with something that extends a Layout, not just a View. – Marcos Vasconcelos Apr 27 '11 at 15:00