尝试膨胀自定义视图时出现stackoverflow错误

时间:2012-05-14 17:21:40

标签: android stack-overflow android-custom-view android-inflate

我有custom_layout.xml:

<?xml version="1.0" encoding="utf-8"?>

<com.example.MyCustomLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

<!-- different views -->

</com.example.MyCustomLayout>

及其班级:

public class MyCustomLayout extends LinearLayout {

public MyCustomLayout(Context context, AttributeSet attrs) {
    super(context, attrs);

    LayoutInflater.from(context).inflate(R.layout.custom_layout, this, true);
    setUpViews();
    }
//different methods
}

活动,包括此布局:

public class MyActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.my_activity);

    setUpViews();
}

和my_activity.xml:

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

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <com.example.MyCustomLayout
        android:id="@+id/section1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" />
    <com.example.MyCustomLayout
        android:id="@+id/section2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" />

</LinearLayout>

因此,当我从LayoutInflater.from(context).inflate(R.layout.custom_layout, this, true);删除评论块并在图形模式下转到my_activity.xml时,我遇到了问题。 Eclipse思考然后崩溃。看起来它试图多次膨胀我的自定义视图,但我不明白为什么。当我重新启动eclipse时,我在错误日志中收到此错误:java.lang.StackOverflowError

2 个答案:

答案 0 :(得分:4)

custom_layout.xml替换<com.example.MyCustomLayout并使用其他布局(例如LinearLayout):

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

<!-- different views -->

</LinearLayout>

甚至更好地使用merge标记(并在orientation类中设置MyCustomLayout)。现在,当Android加载my_activity.xml时,它会找到您的自定义View并将实例化它。在您的自定义视图实例化时,Android会在custom_layout构造函数中膨胀MyCustomLayout xml文件。发生这种情况时,它会再次找到<com.example.MyCustomLayout ...(来自刚刚膨胀的custom_layout.xml),这会导致MyCustomLayout再次被实例化。这是一个递归调用,它最终会抛出StackOverflowError

答案 1 :(得分:0)

此行的存在

LayoutInflater.from(context).inflate(R.layout.custom_layout, this, true);
在自定义布局对象的构造函数中的

导致自相关调用的无限递归,从而溢出堆栈。

你没有理由这样做。

可能你最好的选择是挖掘其他人工作的自定义布局类的例子。

相关问题