Android使用现有视图对象扩充视图

时间:2011-04-26 21:33:28

标签: android methods view static inflate

我有一个自定义视图,我想从资源模板创建。我的自定义视图构造函数接受其他参数,这些参数被设置为自定义视图的附加信息。

问题是当我给视图充气时,我从自定义视图中获取了一个未被子类化的视图对象,因为inflate方法是静态的并且返回一个通用的新视图而不是我的自定义视图的实例。

我想要的是通过传递我的自定义视图对象引用来扩展视图的方法。

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;
    }
}

2 个答案:

答案 0 :(得分:2)

查看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 :(得分:1)

在你的物体上充气。

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