Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/222.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android Can';t初始化Kotlin中对话框中的按钮_Android_Kotlin - Fatal编程技术网

Android Can';t初始化Kotlin中对话框中的按钮

Android Can';t初始化Kotlin中对话框中的按钮,android,kotlin,Android,Kotlin,我有一个浮动操作按钮监听器,里面有alertdialog。我想使用XML中的按钮。如果我想为他们写一个onClickListener() 因此,在Java中,我必须对其进行如下初始化: butAdd = (Button)dialog.findViewById(R.id.btn_add) butAdd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {

我有一个浮动操作按钮监听器,里面有
alertdialog
。我想使用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;
在科特林,这是不正确的

那么,有什么建议可以解决这个问题吗?听众怎么了

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

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()
}

你所在的任何类都没有
findViewById
方法。 您必须在充气布局上
findViewById
,因此:

 var login = linearLayout.findViewById(R.id.login) as EditText
另外,我认为您不需要在对话框上显示
,它不能为空。
另外,我将使您的视图
val
s而不是
var
s。

请使用

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

在活动中导入此行

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

这对我来说很有用。

“这是不正确的”-实际上不是一个精确的描述。它说“未解决的引用:findByView”,并使它成为您刚才所说的redI,但现在它在
var login=linearLayout.findViewById(R.id.login)上抛出了一个TypeCastException,作为EditText
@ПааББББаБааааа1072。一个完整的stracktrace和b。为对话框展开的XML布局。
 btn_submit.setOnClickListener {
            Toast.makeText(this, "hello", Toast.LENGTH_LONG).show();
        }