3

我有 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

4

2 回答 2

4

在您custom_layout.xml替换<com.example.MyCustomLayout为另一个布局(例如 a 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标签(并orientationMyCustomLayout类中设置)。现在Android加载时my_activity.xml它会找到您的自定义View并将其实例化。当您的自定义视图将被实例化时,将在构造函数中Android膨胀custom_layoutxml 文件。MyCustomLayout当这种情况发生时,它将再次<com.example.MyCustomLayout ...(从刚刚膨胀的custom_layout.xml)找到导致MyCustomLayout再次实例化。这是一个递归调用,它最终会抛出StackOverflowError.

于 2012-05-14T17:57:36.023 回答
0

这条线的存在

LayoutInflater.from(context).inflate(R.layout.custom_layout, this, true);

在自定义布局对象的构造函数中导致自依赖调用的无限递归,溢出堆栈。

你没有理由这样做。

也许你最好的选择是挖掘一个其他人工作的自定义布局类的例子。

于 2012-05-14T17:28:44.743 回答