【问题标题】:How to pass additional arguments to a Constructor when extending a LinearLayout in Android?在 Android 中扩展 LinearLayout 时如何将附加参数传递给构造函数?
【发布时间】:2015-08-17 14:34:58
【问题描述】:

如果我有一个扩展 LinearLayout 的类,我有以下问题:

public class ExtendedSeekbarLayout extends LinearLayout { ..}

我想将其他参数传递给我的布局,我该怎么做?我知道我可以有以下构造函数:

 public ExtendedSeekbarLayout (Context context) {
    super(context);

}

public ExtendedSeekbarLayout (Context context, AttributeSet attributeSet) {
    super(context, attributeSet);

}

public ExtendedSeekbarLayout (Context context, AttributeSet attributeSet, int defStyle) {
    super(context, attributeSet, defStyle);

}

但我想要类似的东西:

 public ExtendedSeekbarLayout (Context context, AttributeSet attributeSet, int defStyle, int position) {
    super(context, attributeSet, defStyle);
    init(position);

}

我不确定这是否可行,如果不可行,那该走哪条路?

非常感谢和欢呼,pingu

【问题讨论】:

  • 所以你没有尝试使用你的构造函数?

标签: android class constructor android-linearlayout extend


【解决方案1】:

共享的这个构造函数应该完全按照您的预期工作。

public ExtendedSeekbarLayout (Context context, AttributeSet attributeSet, int defStyle, int position) {
    super(context, attributeSet, defStyle);
    init(position);
}

顺便说一句,你不一定需要这个构造函数,只要你调用

super(context);

如果以编程方式实例化视图,您可以这样做:

public ExtendedSeekbarLayout (Context context, int position) {
    super(context);
    init(position);
}

但是,如果您正在谈论从 xml 发送自定义值,而您实际上并没有调用构造函数,那么您应该看看这个答案: https://stackoverflow.com/a/7608739/2534007

【讨论】:

  • 好的,但是在使用 xml 的情况下,似乎必须预定义自定义值,但在我的情况下,我希望能够为其设置任意值。如果使用编程方法,我知道上下文将是 getActivity().getBaseContext() 但我不确定将什么传递给 attributeSet 和 defStyle。
  • 在 xml 中,只有属性是预定义的,它的值实际上可以是任何你想要的。例如您可以定义位置属性,它的值可以是您想要的任何值。您可以在 xml 中实例化时放置任何值并以编程方式处理该值。如需更好的参考,请参阅:jeffreysambells.com/2010/10/28/…,如果以编程方式进行,请参阅我编辑的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多