【问题标题】:setLayoutParams on Inherited View继承视图上的 setLayoutParams
【发布时间】:2014-06-18 15:06:30
【问题描述】:

我的 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 在 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.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) 在 [...]

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

【问题讨论】:

  • 你试过切换 addView 和 setLayoutParams 行吗?
  • 我有。它崩溃是因为我猜缺少必要的参数......
  • logcat 中一定有什么东西出现了。应用不会无缘无故崩溃。
  • 真的!我有一个 java.lang.StackOverflowError
  • 我没有在工作/不工作中用同一个类实例化 f。有区别:new InheritedView(this) / new ImageView(this)。

标签: java android android-layout inherited-resources


【解决方案1】:

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

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

【讨论】:

  • 真的!没想到……非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多