【问题标题】:Can't initialize the button in dialog in Kotlin无法在 Kotlin 的对话框中初始化按钮
【发布时间】:2016-12-27 16:26:06
【问题描述】:

我有一个浮动操作按钮侦听器,里面有AlertDiaolog。我想使用来自 XML 的按钮。如果我想为他们写一个onClickListener()

所以在 Java 中我必须像这样初始化它:

butAdd = (Button)dialog.findViewById(R.id.btn_add)
butAdd.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        //Some code
    }

但是当我尝试使用时:

var butAdd = dialog?.findViewById(R.id.btn_add) as Button;

在 Kotlin 中是不正确的

那么有什么建议可以解决吗?听众怎么了?

这是我的浮动操作按钮代码:

fab?.setOnClickListener {
    diaolg = AlertDialog.Builder(this@Cards)
    val linearlayout = getLayoutInflater().inflate(R.layout.add_password, null)
    diaolg?.setView(linearlayout)
    ?.setTitle("Add a new password")
    ?.setCancelable(true)

    var login = findViewById(R.id.login) as EditText
    var password = findViewById(R.id.password) as EditText
    var title = findViewById(R.id.title) as EditText

    var butAdd = diaolg?.findViewById(R.id.btn_add) as Button
    var butCancel = diaolg?.findViewById(R.id.btn_cancel) as Button

    butAdd.setOnClickListener(View.OnClickListener {
        fun onClick(v:View){
        }
    })
    butCancel.setOnClickListener(View.OnClickListener {
        fun onClick(v:View){
        }
    })
    diaolg?.create()
    diaolg?.show()
}

【问题讨论】:

  • '这不正确' - 不是一个准确的描述。
  • 它显示“未解析的引用:findByView”并将其变为红色

标签: android kotlin


【解决方案1】:

请通过使用查找id

             var butAdd = linearlayout.findViewById<Button>(R.id.btn_add) as Button;

【讨论】:

    【解决方案2】:

    无论你在哪个班级,都没有 findViewById 方法。 你必须 findViewById 在膨胀的布局上,所以:

     var login = linearLayout.findViewById(R.id.login) as EditText
    

    另外,我认为您不需要在对话框中添加?,它不能为空。 另外,我会让你的意见vals 而不是vars。

    【讨论】:

    • 我刚刚按照你说的做了,但现在它在var login = linearLayout.findViewById(R.id.login) as EditText上抛出了一个 TypeCastException
    • @ПавелБределев 您应该提供一个。完整的 stracktrace 和 b。您为对话框扩展的 XML 布局。
    【解决方案3】:

    在您的活动中导入这一行

    <Button
            android:id="@+id/btn_submit"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="submit" />
    

    在您的 Activity 中导入这一行

    // 使用主源集中的 R.layout.activity_main

    //activity_main 是你的布局文件名

    导入 kotlinx.android.synthetic.main.activity_main.*

     btn_submit.setOnClickListener {
                Toast.makeText(this, "hello", Toast.LENGTH_LONG).show();
            }
    

    它对我有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-18
      • 2011-01-04
      • 2021-04-24
      • 1970-01-01
      • 2013-03-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多