以下是我的自定义视图:
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中获取自定义视图。你知道为什么吗?
答案 0 :(得分: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));