在Kotlin Android中未解决的对函数的引用

我在我的MainActivity中有以下onCreate函数。

 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) var selected_answer = 0 val btn_list = mutableListOf<ToggleButton>(button1, button2, button3, button4) for(i in btn_list){ i.setOnClickListener{ toggle_rest(btn_list.indexOf(i), btn_list) selected_answer = btn_list.indexOf(i)+1 } } fun toggle_rest(toCheck : Int, btn_list : List<ToggleButton>){ for (i in btn_list) { i.setChecked(btn_list.indexOf(i) == toCheck) } } question_txt.setText("Quiz will begin shortly!") } 

当我调用toggle_rest ,会出现错误toggle_rest:Unresolved reference

在代码中使用之前,您必须先定义toggle_rest函数,否则会得到unresolve引用编译错误:

 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) var selected_answer = 0 //Declare your function before you use fun toggle_rest(toCheck : Int, btn_list : List<ToggleButton>){ for (i in btn_list) { i.setChecked(btn_list.indexOf(i) == toCheck) } } val btn_list = mutableListOf<ToggleButton>(button1, button2, button3, button4) for(i in btn_list){ i.setOnClickListener{ toggle_rest(btn_list.indexOf(i), btn_list) selected_answer = btn_list.indexOf(i)+1 } } question_txt.setText("Quiz will begin shortly!") } 

您也可以在onCreate()方法之外定义函数,如下所示。

 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) var selected_answer = 0 val btn_list = mutableListOf<ToggleButton>(button1, button2, button3, button4) for(i in btn_list){ i.setOnClickListener{ toggle_rest(btn_list.indexOf(i), btn_list) selected_answer = btn_list.indexOf(i)+1 } } question_txt.setText("Quiz will begin shortly!") } fun toggle_rest(toCheck : Int, btn_list : List<ToggleButton>){ for (i in btn_list) { i.setChecked(btn_list.indexOf(i) == toCheck) } } 

根据您的期望工作。