You cannot declare a custom view like you. If you use your regular view in the main layout, the onFinishInflate method will be called to create a custom view, and the layout above will be called in this method. The problem is that you already have a custom view link in this layout (which will be bloated again when LayoutInflater encounters a custom view tag) so that you get into a circular bloat situation.
You probably want something like this:
<merge xmlns:android="http://schemas.android.com/apk/res/android> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="custom button 1"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="custom button 2"/> </merge>
so when your custom view is inflated from the layout file, it will add the contents of the xml layout above. The onFinishInflate method will remain the same:
@Override protected void onFinishInflate() { super.onFinishInflate(); LayoutInflater.from(getContext()).inflate(R.layout.test_view, this);
Change It seems that inflating the content layout in the onFinishInflate method calls the method again (at least in older versions). You can either change the layout to use LinearLayout as follows:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="custom button 1"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="custom button 2"/> </LinearLayout>
and then in the onFinishInflate method:
@Override protected void onFinishInflate() { super.onFinishInflate(); View v = LayoutInflater.from(getContext()).inflate(R.layout.aaaaaaaaaaa, this, false); addView(v); }
This will cause another useless item to appear in the layout hierarchy, so you can simply inflate the layout with the merge tag in the custom view constructors:
public MyView(Context context) { super(context); LayoutInflater.from(getContext()).inflate(R.layout.test_view, this); } public MyView(Context context, AttributeSet attrs) { super(context, attrs); LayoutInflater.from(getContext()).inflate(R.layout.test_view, this); } public MyView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); LayoutInflater.from(getContext()).inflate(R.layout.test_view, this); }