2

这是我的自定义视图:

public class BuzzView extends View {

    /**
     * Constructor.  This version is only needed if you will be instantiating
     * the object manually (not from a layout XML file).
     * @param context
     */
    public BuzzView(Context context) {
        super(context);
        View.inflate(context, R.layout.buzz_view, null);
    }
}

我的buzz_view.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:id="@+id/vignette_image_jauge"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentRight="true"
        android:src="@drawable/buzzomettre_sample" >
    </ImageView>

</RelativeLayout>

比我想在我的活动中从我的 FrameLayout 添加我的自定义视图:

 BuzzView buzzView = new BuzzView(MosaiqueListActivity.this);
    FrameLayout frameLayout = (FrameLayout) 
v.findViewById(R.id.vignette_layout_jauge);
                frameLayout.addView(buzzView);

我没有在我的 RelativeLayout 中获得我的自定义视图。你知道为什么吗?

4

1 回答 1

1

尝试像这样创建您的 BuzzView

public class CustomView {

private Context mContext;
private View mCustomView;
private LayoutInflater mInflater;
public CustomView(Context context) {
    // TODO Auto-generated constructor stub
    mContext = context;
    mInflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

public View getView() {
    if(mCustomView==null) {
        mCustomView = mInflater.inflate(R.layout.customView, null);
        //initialize all the child here
    }
    return mCustomView;
}
}

在添加视图时,只需在您的活动中调用 getView() 方法

CustomView mCustomView = new CustomView(MyActivity.this);
layout.addView(mCustomView.getView(), new LayoutParams(LayoutParams.WRAP_CONTENT,    LayoutParams.WRAP_CONTENT));
于 2013-01-31T12:08:41.077 回答