无法在Kotlin中的对话框中初始化按钮

时间:2016-12-27 16:26:06

标签: android kotlin

我有一个内置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()
}

3 个答案:

答案 0 :(得分:1)

请使用

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

答案 1 :(得分:0)

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

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

另外,我认为您不需要在对话框中使用?,它不能为空。 另外,我会将您的观看次数val s而不是var s。

答案 2 :(得分:0)

在您的活动中导入此行

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

在您的活动

中导入此行

//使用主要源集

中的R.layout.activity_main

// activity_main是您的布局文件名

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

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

它为我工作。