0

我的 android 应用程序有问题。我想通过这样做创建一个新视图:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


}

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    LinearLayout l = (LinearLayout)findViewById(R.id.mainActivity);
    f = new InheritedView(this);
    f.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));
    l.addView(f);
}

public class InheritedView extends ImageView implements AbstractView 

public InheritedView(Context context) {
    super(context);
}

但是当我测试它时,我的应用程序在执行 setLayoutParams(..) 时因 java.lang.StackOverflowError 而崩溃。但是,以下工作:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    LinearLayout l = (LinearLayout)findViewById(R.id.mainActivity);
    f = new ImageView(this);
    f.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));
    l.addView(f);
}

LOGCAT 文件

致命异常:主进程:fr.cameleoz.nemo,PID:30304 java.lang.StackOverflowError at fr.cameleoz.nemo.business.factories.nemoviews.impl.InheritedView.setLayoutParams(InheritedView.java:32) at fr.cameleoz。 nemo.business.factories.nemoviews.impl.InheritedView.setLayoutParams(InheritedView.java:32) 在 fr.cameleoz.nemo.business.factories.nemoviews.impl.InheritedView.setLayoutParams(InheritedView.java:32) 在 fr.cameleoz。 nemo.business.factories.nemoviews.impl.InheritedView.setLayoutParams(InheritedView.java:32) 在 fr.cameleoz.nemo.business.factories.nemoviews.impl.InheritedView.setLayoutParams(InheritedView.java:32) 在 fr.cameleoz。 nemo.business.factories.nemoviews.impl.InheritedView.setLayoutParams(InheritedView.java:32) 在 fr.cameleoz.nemo.business。factory.nemoviews.impl.InheritedView.setLayoutParams(InheritedView.java:32) 在 fr.cameleoz.nemo.business.factories.nemoviews.impl.InheritedView.setLayoutParams(InheritedView.java:32) 在 fr.cameleoz.nemo.business。 factory.nemoviews.impl.InheritedView.setLayoutParams(InheritedView.java:32) 在 [...]

你能解释一下为什么吗?谢谢

4

1 回答 1

0

根据堆栈跟踪,您的InheritedView覆盖setLayoutParams()和被覆盖的方法会自行调用。

每个嵌套方法调用都会占用一些堆栈空间,并且这种无限递归只会在堆栈用完时终止。

于 2014-06-18T15:54:05.777 回答