我有一个 Android 应用程序,它生成 5 个 5 个数字的列表。
其次,点击“选择号码”后,它将删除重复的号码,并将生成的所有号码打印为按钮。
我的程序在 MainActivity.kt
的这段代码上崩溃val generatedNumbersCollected: Button = findViewById(R.id.root)
generatedNumbersCollected.setOnClickListener {
Toast.makeText(this, "Clicked 1", Toast.LENGTH_SHORT).show()
}
我假设
R.id.root
为空,因此它崩溃了。我正在寻找解决此问题的方法。可能的解决方案是什么?
MainActivity.kt
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.constraintlayout.helper.widget.Flow
import androidx.constraintlayout.widget.ConstraintLayout
import kotlin.random.Random
class MainActivity : ComponentActivity() {
private var concat: Set<Int> = emptySet()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val generateButton: Button = findViewById(R.id.buttonGenerate)
val selNumbers: Button = findViewById(R.id.selectNumbers)
val numberGenerated: TextView = findViewById(R.id.numberGenerated)
val numberGenerated2: TextView = findViewById(R.id.numberGenerated2)
val numberGenerated3: TextView = findViewById(R.id.numberGenerated3)
val numberGenerated4: TextView = findViewById(R.id.numberGenerated4)
val numberGenerated5: TextView = findViewById(R.id.numberGenerated5)
val collectedNumbers: TextView = findViewById(R.id.collectedNumbers)
//var addBtn: Button? = null
//linearLayout = findViewById(R.id.linearLayout)
generateButton.setOnClickListener {
val randomNumbers = generateSequence {
Random.nextInt(1..70)
}.distinct().take(5).sorted().toSet()
val randomNumbers2 = generateSequence {
Random.nextInt(1..70)
}.distinct().take(5).sorted().toSet()
val randomNumbers3 = generateSequence {
Random.nextInt(1..70)
}.distinct().take(5).sorted().toSet()
val randomNumbers4 = generateSequence {
Random.nextInt(1..70)
}.distinct().take(5).sorted().toSet()
val randomNumbers5 = generateSequence {
Random.nextInt(1..70)
}.distinct().take(5).sorted().toSet()
concat = concatenate(
randomNumbers,
randomNumbers2,
randomNumbers3,
randomNumbers4,
randomNumbers5
)
numberGenerated.text = randomNumbers.toString()
numberGenerated2.text = randomNumbers2.toString()
numberGenerated3.text = randomNumbers3.toString()
numberGenerated4.text = randomNumbers4.toString()
numberGenerated5.text = randomNumbers5.toString()
}
selNumbers.setOnClickListener {
numberGenerated.text = "none"
numberGenerated2.text = "none"
numberGenerated3.text = "none"
numberGenerated4.text = "none"
numberGenerated5.text = "none"
collectedNumbers.text = concat.toString()
createAndAddView()
//val intent = Intent(this@MainActivity, SelectNumbers::class.java)
//startActivity(intent)
}
/*val generatedNumbersCollected: Button = findViewById(R.id.root)
generatedNumbersCollected.setOnClickListener {
Toast.makeText(this, "Clicked 1", Toast.LENGTH_SHORT).show()
}*/
}
private fun createAndAddView()
{
val root = findViewById<ConstraintLayout>(R.id.root)
lateinit var button: Button
val array: IntArray = concat.toIntArray()
for ((index, i) in array.withIndex()) {
button = Button(this).apply {
layoutParams = ViewGroup.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT)
id = index + 1
text = i.toString()
}
root.addView(button)
}
val flow = findViewById<Flow>(R.id.flow)
flow.referencedIds = (1 .. array.size).toList().toIntArray()
}
}
private fun Random.nextInt(range: IntRange): Int {
return range.first + nextInt(range.last - range.first)
}
private fun concatenate(
randomNumbers: Set<Int>,
randomNumbers2: Set<Int>,
randomNumbers3: Set<Int>,
randomNumbers4: Set<Int>,
randomNumbers5: Set<Int>
): Set<Int> {
return randomNumbers + randomNumbers2 + randomNumbers3 + randomNumbers4 + randomNumbers5
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/MainActivity"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="@+id/selectedRandom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Selected Random" />
<TextView
android:id="@+id/numberGenerated"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="List Number 1" />
<TextView
android:id="@+id/numberGenerated2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="List Number 2" />
<TextView
android:id="@+id/numberGenerated3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="List Number 3" />
<TextView
android:id="@+id/numberGenerated4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="List Number 4" />
<TextView
android:id="@+id/numberGenerated5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="List Number 5" />
<TextView
android:id="@+id/collectedNumbers"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="none" />
<Button
android:id="@+id/buttonGenerate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Generate" />
<Button
android:id="@+id/selectNumbers"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select Numbers" />
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fillViewport="true">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.constraintlayout.helper.widget.Flow
android:id="@+id/flow"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:flow_horizontalGap="8dp"
app:flow_maxElementsWrap="5"
app:flow_verticalGap="8dp"
app:flow_verticalStyle="packed"
app:flow_wrapMode="aligned" />
</androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>
这是日志猫:
FATAL EXCEPTION: main
Process: com.example.randomgenerator, PID: 19302
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.randomgenerator/com.example.randomgenerator.MainActivity}: java.lang.ClassCastException: androidx.constraintlayout.widget.ConstraintLayout cannot be cast to android.widget.Button
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.ClassCastException: androidx.constraintlayout.widget.ConstraintLayout cannot be cast to android.widget.Button
at com.example.randomgenerator.MainActivity.onCreate(MainActivity.kt:84)
at android.app.Activity.performCreate(Activity.java:7994)
at android.app.Activity.performCreate(Activity.java:7978)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
我尝试复制您的代码,并可以通过单击按钮来解决该问题,并通过对此功能进行更改来获取结果
private fun createAndAddView() {
val root = findViewById<ConstraintLayout>(R.id.root)
lateinit var button: Button
val array: IntArray = concat.toIntArray()
for ((index, i) in array.withIndex()) {
button = Button(this).apply {
layoutParams = ViewGroup.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT)
id = index + 1
text = i.toString()
// add this code
setOnClickListener {
Toast.makeText(this@MainActivity, "Clicked ${i}", Toast.LENGTH_SHORT).show()
}
}
root.addView(button)
}
val flow = findViewById<Flow>(R.id.flow)
flow.referencedIds = (1..array.size).toList().toIntArray()
}
但是,实际上我的建议是实现 recyclerview 将使您的代码更加干净和简单,而不是像这样生成流程。很高兴编码:)