如何使按钮在片段中工作(Kotlin)



我有一个活动片段,让它从一个单独的数据类和一个.xml文件中调用值

我希望.xml文件中的按钮可以在Kotlin CLASS中访问。但是,一个错误不断显示声明的函数不可访问。我所做的:

科特林课堂页面:

class HomeFragment : Fragment() {
private val personcolletionref =Firebase.firestore.collection( "users")
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false)
submitbutton.setOnClickListener {
}
}
private fun savePerson (person: Person) = CoroutineScope(Dispatchers.IO).launch {
try {
personcolletionref.add(person).await()
withContext(Dispatchers.Main) {
Toast.makeText(activity, "Successful", Toast.LENGTH_LONG).show()
}
}catch (e: Exception) {
withContext(Dispatchers.Main) {
Toast.makeText(activity, e.message, Toast.LENGTH_LONG).show()
}
}
}

}

xml文件中要调用的按钮:

<Button
android:id="@+id/submitbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="268dp"
android:text="Submit"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="@+id/edittextage"
app:layout_constraintStart_toStartOf="@+id/edittextage" />

在onCreateView方法中,您只需要返回视图。重写以下方法,并在点击监听器init上编写按钮

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
submitbutton.setOnClickListener {
}
}

最新更新