我有 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
}
和 Activity ,其中包括此布局:
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>
所以,当我从以下位置删除注释 block 时遇到问题:LayoutInflater.from(context).inflate(R.layout.custom_layout, this, true);
并转到图形模式。 Eclipse 思考然后崩溃。看起来它试图多次膨胀我的自定义 View ,但我不明白为什么。当我重新启动 eclipse 时,我在错误日志中收到此错误:java.lang.StackOverflowError
最佳答案
在你的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
它将实例化它。当您的自定义 View 被实例化时 Android
将使 custom_layout
膨胀MyCustomLayout
中的 xml 文件构造函数。发生这种情况时,它将再次找到 <com.example.MyCustomLayout ...
(来自刚刚膨胀的 custom_layout.xml
)导致 MyCustomLayout
再次被实例化。这是一个递归调用,它最终会抛出 StackOverflowError
。 .
关于android - 尝试膨胀自定义 View 时出现 stackoverflow 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10588109/