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

blu*_*yte 4 stack-overflow android 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>
Run Code Online (Sandbox Code Playgroud)

及其类别:

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
}
Run Code Online (Sandbox Code Playgroud)

和活动,其中包括以下布局:

public class MyActivity extends Activity {

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

    setUpViews();
}
Run Code Online (Sandbox Code Playgroud)

和 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>
Run Code Online (Sandbox Code Playgroud)

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

Luk*_*rog 5

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>
Run Code Online (Sandbox Code Playgroud)

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