Here are my custom view:
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);
}
}
My 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>
Than i want to add my custom view from my FrameLayout in my activity:
BuzzView buzzView = new BuzzView(MosaiqueListActivity.this);
FrameLayout frameLayout = (FrameLayout)
v.findViewById(R.id.vignette_layout_jauge);
frameLayout.addView(buzzView);
I am not getting my custom view in my RelativeLayout. Do you know why?
asked Jan 31, 2013 at 10:55
haythem souissi
3,2837 gold badges52 silver badges79 bronze badges
-
try adding layout paramsSwati– Swati2013年01月31日 10:57:45 +00:00Commented Jan 31, 2013 at 10:57
-
doesn't work :( buzzView.setLayoutParams(new AbsListView.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));haythem souissi– haythem souissi2013年01月31日 10:59:18 +00:00Commented Jan 31, 2013 at 10:59
-
is it possible to cast a ImageView to FrameLayout??edwin– edwin2013年01月31日 11:01:57 +00:00Commented Jan 31, 2013 at 11:01
-
You need to Implement all three constructor from superclass. Also don't extends directly from View, user RelativeLayout as superclass insteadThommy– Thommy2013年01月31日 11:04:46 +00:00Commented Jan 31, 2013 at 11:04
-
there is a classcastexception in the code you postednjzk2– njzk22013年01月31日 11:05:34 +00:00Commented Jan 31, 2013 at 11:05
1 Answer 1
Try creating your BuzzView like this
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;
}
}
while adding your view just call getView() method like this in your activity
CustomView mCustomView = new CustomView(MyActivity.this);
layout.addView(mCustomView.getView(), new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
Sign up to request clarification or add additional context in comments.
Comments
default