我的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
。
答案 0 :(得分:1)
在使用代码之前,必须先定义toggle_rest
函数,否则将获得 unresolve reference 编译错误:
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!")
}
答案 1 :(得分:0)
您还可以在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)
}
}
按照您的期望工作。