我是一个kotlin的初学者,正在尝试开发一些样例项目。我尝试使用View.OnClickListener接口来获取在我的布局中单击的任何视图的Id。我的布局中有9个按钮(三连棋游戏),但运行代码后单击任何按钮都不会发生任何事情,甚至没有显示任何错误。
class MainActivity : AppCompatActivity(), View.OnClickListener {
private lateinit var binding : ActivityMainBinding
var active = 1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
}
override fun onClick(view: View?) {
val button = view as Button
button.setBackgroundColor(Color.parseColor("#ffffff"))
if(active == 1) {
button.text = "X"
button.setTextColor(Color.parseColor("#FF6200EE"))
button.textSize = 20f
button.isEnabled = false
active = 0
}
else {
button.text = "O"
button.setTextColor(Color.parseColor("#FF6200EE"))
button.textSize = 20f
button.isEnabled = false
active = 1
}
}
}
XML文件
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".MainActivity"
android:background="#F6F6F6">
<TableLayout
android:id="@+id/tlTableLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent">
<TableRow
android:id="@+id/trRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="@+id/bnOne"
android:layout_width="40pt"
android:layout_height="40pt"
android:layout_marginRight="5pt"/>
<Button
android:id="@+id/bnTwo"
android:layout_width="40pt"
android:layout_height="40pt"
android:layout_marginRight="5pt"/>
<Button
android:id="@+id/bnThree"
android:layout_width="40pt"
android:layout_height="40pt"/>
</TableRow>
<TableRow
android:id="@+id/trRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="@+id/bnFour"
android:layout_width="40pt"
android:layout_height="40pt"
android:layout_marginRight="5pt"/>
<Button
android:id="@+id/bnFive"
android:layout_width="40pt"
android:layout_height="40pt"
android:layout_marginRight="5pt"/>
<Button
android:id="@+id/bnSix"
android:layout_width="40pt"
android:layout_height="40pt"/>
</TableRow>
<TableRow
android:id="@+id/trRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="@+id/bnSeven"
android:layout_width="40pt"
android:layout_height="40pt"
android:layout_marginRight="5pt"/>
<Button
android:id="@+id/bnEight"
android:layout_width="40pt"
android:layout_height="40pt"
android:layout_marginRight="5pt"/>
<Button
android:id="@+id/bnNine"
android:layout_width="40pt"
android:layout_height="40pt"/>
</TableRow>
</TableLayout>
</androidx.constraintlayout.widget.ConstraintLayout>