【问题标题】:Way to initialize variable by passing into a class通过传递给类来初始化变量的方法
【发布时间】:2016-01-18 16:49:24
【问题描述】:

其实我是想把一个变量类型Id传入一个类来初始化变量。

喜欢,Button myButton=new MyClass(Button, myButtonId);

这里Button是变量类型,myButtonId是xml中的id。

并且类(方法)将返回类似(Button)findViewById(R.id.myButtonId);

为此我写了

Button myButton=new MyClass(Button, myButtonId);

Android Studio 建议我

private class MyClass extends Button {
        public MyClass(Object p, Button myButtonId) {
            super();
        }
    }

super(); 行有错误。

我不知道要做更多。 有什么建议吗?

【问题讨论】:

  • 你可以使用setter和getter
  • 在 super() 中使用什么;因为有错误?
  • 检查构造函数@grepcode.com/file/repository.grepcode.com/java/ext/… 只是传递上下文
  • 类会返回类似的东西——类不会返回,它们会封装。我很困惑你为什么要这样做?
  • 其实我是说方法

标签: android class variables


【解决方案1】:

你需要在超级函数中放置至少一个(上下文)参数 请在此处检查 Button 类的公共构造函数: Button public constructors

更新

您需要将上下文传递给扩展 Button 的类,如下所示:

MyClass myButton = new MyClass(getApplicationContext());

然后在你的 MyClass 中:

public class MyClass extends Button {
    public MyClass(Context context) {
        super(context);
    }
}

【讨论】:

  • Button 也有错误(作为参数传递时)。
  • 但是传递 id 呢?
  • 尝试使用上面链接中显示的属性集
猜你喜欢
  • 2018-03-14
  • 1970-01-01
  • 2022-10-15
  • 2022-07-19
  • 1970-01-01
  • 2014-09-10
  • 2019-11-07
  • 2021-03-26
  • 2017-02-23
相关资源
最近更新 更多