Kotlin 代码报告“无法解析 AndroidManifest.xml 中用于 Kotlin Android 开发的符号‘@style/Theme.Androidstudio’”

问题描述 投票:0回答:1

我正在使用一些功能制作一个 Kotlin 项目

代码的作用如下-

从微调器中获取用户名 从单选按钮中获取预算标题 显示 toast 消息后,它会导航到另一个页面

输入必填字段后,有三个按钮可以执行以下操作 -

点击按钮1后,会出现一条Toast消息,显示总成本 单击按钮2后,会显示一个警报对话框,说明预算是否大于支出,反之亦然 重定向到带有列表视图和网格视图的新页面 我遇到一些错误 -

        android:id="@+id/lsview"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"

我尝试过清理和重建项目、同步 Gradle 文件,甚至重新启动 Android Studio,但错误仍然存在。

除了解决此错误之外,我还在寻求有关在 Kotlin Android 应用程序中实现 CRUD 操作的指导。任何与 Kotlin 中的 CRUD 操作相关的建议、资源或示例将不胜感激。

主页.xml

(包含汉堡菜单/数据库创建/数据库插入/意图)

<ScrollView
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/title"
        app:layout_constraintVertical_bias="0.355">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:padding="16dp">

        </LinearLayout>
    </ScrollView>

<GridLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingHorizontal="16dp"
                android:alignmentMode="alignMargins"
                android:useDefaultMargins="true"
                android:padding="16dp"
                android:rowCount="1"
                android:columnCount="3">
</GridLayout>


选项菜单.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/change_color"
        android:title="Change Font Color"/>
    <item
        android:id="@+id/change_style"
        android:title="Change Font Style"/>
    <item
        android:id="@+id/reset_default"
        android:title="Reset to Default"/>
</menu>

主要活动.kt

import android.content.Intent
import android.database.sqlite.SQLiteDatabase
import android.graphics.Color
import android.graphics.Typeface
import android.os.Bundle
import android.text.TextUtils
import android.util.Patterns
import android.view.Menu
import android.view.MenuItem
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit


class MainActivity : AppCompatActivity() {
    private lateinit var titleTextView:TextView// For burger menu
    private lateinit var db:SQLiteDatabase   //For SQL
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        //menu code
        val toolbar: Toolbar = findViewById(R.id.toolbar)
        setSupportActionBar(toolbar)
         titleTextView = findViewById<TextView>(R.id.title)

        val name=findViewById<EditText>(R.id.namei)
        val id=findViewById<EditText>(R.id.idi)
        val emailid=findViewById<EditText>(R.id.emaili)
        val phno=findViewById<EditText>(R.id.phi)
        val startd=findViewById<EditText>(R.id.sdi)
        val rent=findViewById<EditText>(R.id.renti)
        val endd=findViewById<EditText>(R.id.edi)
        val food=findViewById<EditText>(R.id.foodi)


        //Code for button to go to next page with validation
        val submit1=findViewById<Button>(R.id.sub1)
        submit1.setOnClickListener {

            var namestr=name.text.toString()
            var idint:Int=id.text.toString().toIntOrNull()?:0
            var emailstr=emailid.text.toString()
            var phnostr=phno.text.toString()
            var startstr=startd.text.toString()
            var rentint:Int=rent.text.toString().toIntOrNull()?:0
            var endstr=endd.text.toString()
            var foodstr=food.text.toString()

            var flag=0
            if(!isValidEmail(emailstr))
            {
                Toast.makeText(this, "Invalid Email", Toast.LENGTH_SHORT).show()
                emailid.error="Invalid Email"
                flag=1
            }

            if(!isValidPho(phnostr))
            {
                Toast.makeText(this, "phone no only contains digits", Toast.LENGTH_SHORT).show()
                phno.error="Invalid Phone num "
                flag=1
            }

            if(!isValidName(namestr))
            {
                Toast.makeText(this, "Only Letters", Toast.LENGTH_SHORT).show()
                name.error="Only Letters "
                flag=1
            }

            if(!isValidDate(startstr))
            {
                Toast.makeText(this, "Invalid date", Toast.LENGTH_SHORT).show()
                startd.error="Invalid date "
                flag=1
            }
            if(!isValidDate(endstr))
            {
                Toast.makeText(this, "Invalid date", Toast.LENGTH_SHORT).show()
                endd.error="Invalid date "
                flag=1
            }


            if(flag==0){
            val intent= Intent(this,Page2::class.java).apply {
                putExtra("name",namestr)
                putExtra("id",idint)
                putExtra("email",emailstr)
                putExtra("phno",phnostr)
                putExtra("start",startstr)
                putExtra("rent",rentint)
                putExtra("end",endstr)
                putExtra("food",foodstr)

            }

            startActivity(intent)
            }
        }

        //code for button to add to database
        
        db=openOrCreateDatabase("endsem.db", MODE_PRIVATE,null)
        val createTableQuery= "CREATE TABLE IF NOT EXISTS person(id INT PRIMARY KEY,name TEXT,email TEXT,phone TEXT,start_date TEXT,Rent INT,end_date TEXT,Food TEXT)"
        db?.execSQL(createTableQuery)

        val AddtoDB=findViewById<Button>(R.id.Addtodb)
        AddtoDB.setOnClickListener {
            var namestr=name.text.toString()
            var idint:Int=id.text.toString().toIntOrNull()?:0
            var emailstr=emailid.text.toString()
            var phnostr=phno.text.toString()
            var startstr=startd.text.toString()
            var rentint:Int=rent.text.toString().toIntOrNull()?:0
            var endstr=endd.text.toString()
            var foodstr=food.text.toString()

            val insertQuery="insert into person VALUES($idint,'$namestr','$emailstr','$phnostr','$startstr',$rentint,'$endstr','$foodstr')"
            db?.execSQL(insertQuery)
            Toast.makeText(this@MainActivity, "Inserted Data Successfully!",Toast.LENGTH_SHORT).show()


        }


    }
    
    //Code for validation functions
    
    private fun isValidEmail(email: String): Boolean {
        return !TextUtils.isEmpty(email) && Patterns.EMAIL_ADDRESS.matcher(email).matches()
    }

    private fun isValidPho(phone:String):Boolean{
        return phone.length == 10 && phone.all { it.isDigit() }
    }
    private fun isValidName(name:String):Boolean{
        return name.all {it.isLetter()|| it.isWhitespace()}
    }

    private fun isValidDate(date:String):Boolean{
        val parts = date.split("-")
        if (parts.size != 3) return false

        val day = parts[0]
        val month = parts[1]
        val year = parts[2]
        if (day.length != 2 || month.length != 2 || year.length != 4) return false

        return day.all { it.isDigit() } && month.all { it.isDigit() } && year.all { it.isDigit() }
    }

    //CODE FOR BURGER MENU see xml from options_menu.xml stored in separate directory menu
      
    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.options_menu, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.change_color -> {
                titleTextView.setTextColor(Color.BLUE)
                true
            }
            R.id.change_style -> {
                titleTextView.setTypeface(titleTextView.typeface, Typeface.BOLD_ITALIC)
                true
            }
            R.id.reset_default -> {
                titleTextView.setTextColor(Color.BLACK)
                titleTextView.setTypeface(Typeface.DEFAULT, Typeface.NORMAL)
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }

}

Page2.xml(包含Listview中的Disp)

 <Button
        android:id="@+id/disp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="28dp"
        android:text="Display all"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0"
        tools:ignore="HardcodedText" />

    <HorizontalScrollView
        android:layout_width="409dp"
        android:layout_height="561dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <ListView
            android:id="@+id/lsview"
            android:layout_width="347dp"
            android:layout_height="357dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            tools:layout_editor_absoluteX="32dp"
            tools:layout_editor_absoluteY="117dp" />
    </HorizontalScrollView>

第2页.kt

import android.content.Intent
import android.database.sqlite.SQLiteDatabase
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.EditText
import android.widget.ListView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class Page2 : AppCompatActivity() {
    private lateinit var db: SQLiteDatabase
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_page2)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        //RECIEVE INTENT
        val namez = intent.getStringExtra("name")
        val idz = intent.getIntExtra("id", 0)
        val emailz = intent.getStringExtra("email")
        val phonez = intent.getStringExtra("phno")
        val startz = intent.getStringExtra("start")
        val rentz = intent.getIntExtra("rent", 0)
        val endz = intent.getStringExtra("end")
        val foodz = intent.getStringExtra("food")

        val message = """
        Name: $namez
        ID: $idz
        Email: $emailz
        Phone: $phonez
        Start Date: $startz
        Rent: $rentz
        End Date: $endz
        Food Preference: $foodz
    """.trimIndent()
        
        //ALERT DIALOG CODE
        AlertDialog.Builder(this)
            .setTitle("Confirmation Details")
            .setMessage(message)
            .setPositiveButton("Dismiss") { dialog,which ->
                dialog.dismiss()
            }
            .show()

        //LISTVIEW CODE AND DB SELECT CODE 
        val dataList = ArrayList<String>()
        val listview=findViewById<ListView>(R.id.lsview)

        db = openOrCreateDatabase("endsem.db", MODE_PRIVATE,null)
        val dispbutton=findViewById<Button>(R.id.disp)
        dispbutton.setOnClickListener {
            val dispQuery="Select * from person order by name desc"
            val cursor=db?.rawQuery(dispQuery,null)
            while(cursor!!.moveToNext()){
                val id = cursor.getInt(0)
                val name = cursor.getString(1)
                val email = cursor.getString(2)
                val phone = cursor.getString(3)
                val start = cursor.getString(4)
                val rent = cursor.getInt(5)
                val end = cursor.getString(6)
                val food=cursor.getString(7)

                val displayString = "ID: $id, Name: $name, Email: $email," +
                        " Phone: $phone, Start: $start, " +
                        "Rent: $rent, End: $end, Food: $food"
                dataList.add(displayString)
            }
            cursor.close()

            //LISTVIEW CODE
            val listadapter= ArrayAdapter(
                this,
                android.R.layout.simple_list_item_1
                ,dataList)
            listview.adapter=listadapter
            listview.setOnItemClickListener{_,_,position,_->
                val selecteditem=dataList[position]
                Toast.makeText(this, "Item selected is $selecteditem", Toast.LENGTH_SHORT).show()
            }


        }

        val total=findViewById<Button>(R.id.TotalRent)
        total.setOnClickListener {
            val intent= Intent(this,Page3::class.java)
            startActivity(intent)
        }
        //BACK BUTTON CODE
        val back=findViewById<Button>(R.id.Back)
        back.setOnClickListener {
            finish()
        }


    }
}

Page3.kt(使用chronro和DB SELECT计算总金额)

import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit

val datalist=ArrayList<String>()
        val listview=findViewById<ListView>(R.id.ls)

        db=openOrCreateDatabase("endsem.db", MODE_PRIVATE,null)
        val disp=findViewById<Button>(R.id.Disprent)
        disp.setOnClickListener {
            val dispQuery="select name,start_date,Rent,end_date from person "
            val cursor=db?.rawQuery(dispQuery,null)
            while(cursor!!.moveToNext())
            {
                val name=cursor.getString(0)
                val start=cursor.getString(1)
                val rent=cursor.getInt(2)
                val end=cursor.getString(3)

                var totalrent=findTotalRent(start,rent,end)
                val displayString="Name: $name, Start_Date: $start, Rent: $rent, End_date: $end, Total_Rent: $totalrent"
                datalist.add(displayString)

            }
            cursor.close()

            val listAdapter = ArrayAdapter(
                this,android.R.layout.simple_list_item_1,datalist
            )
            listview.adapter=listAdapter

        }

private fun findTotalRent(start: String, rent: Int, end: String): Int {
        val formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy")
        val startDate = LocalDate.parse(start, formatter)
        val endDate = LocalDate.parse(end, formatter)
        val noOfDays = ChronoUnit.DAYS.between(startDate, endDate)
        return (noOfDays * rent).toInt()

    }

Page4.kt(交互式列表视图/删除/更新代码)

db=openOrCreateDatabase("endsem.db", MODE_PRIVATE,null)

        val edittxt=findViewById<EditText>(R.id.edt)
        val edittxt2=findViewById<EditText>(R.id.edt2)

        val update=findViewById<Button>(R.id.update)
        update.setOnClickListener {

            val name=edittxt.text.toString()
            val rent=edittxt2.text.toString().toInt()

            val updateQuery="Update person set Rent=$rent where name= '$name'"
            db?.execSQL(updateQuery)
            Toast.makeText(this, "Updated Successfully", Toast.LENGTH_SHORT).show()

        }

        val delete=findViewById<Button>(R.id.delete)
        delete.setOnClickListener {

            val name=edittxt.text.toString()
            val delQuery="Delete from person where name='$name'"
            db?.execSQL(delQuery)
            Toast.makeText(this, "Deleted Successfully", Toast.LENGTH_SHORT).show()

        }

 val listView=findViewById<ListView>(R.id.ls)
        val txt=findViewById<TextView>(R.id.txt)

        val datalist=ArrayList<String>()
        val fetchQuery="Select distinct food from person"
        val cursor=db?.rawQuery(fetchQuery,null)
        while(cursor!!.moveToNext())
        {
            val food=cursor.getString(0)
            datalist.add(food)
        }
        cursor.close()
        val listadapter=ArrayAdapter(this,android.R.layout.simple_list_item_1,datalist)
        listView.adapter=listadapter

        listView.setOnItemClickListener{_,_,position,_->
            val selecteditem=datalist[position]
            Toast.makeText(this, "Item selected is $selecteditem", Toast.LENGTH_SHORT).show()
            val showQuery="select id,name from person where food='$selecteditem'"
            val dispstring=StringBuilder()
            val cursor2=db?.rawQuery(showQuery,null)
            while (cursor2!!.moveToNext())
            {
                val id=cursor2.getInt(0)
                val name=cursor2.getString(1)
                val msg="ID: $id ,Name: $name "
                dispstring.append(msg)

            }
            cursor2.close()
            txt.text=dispstring.toString()

        }

Page5.kt(包含微调器/在微调器本身中显示)

private var userHasInteracted = false

val spin=findViewById<Spinner>(R.id.spin)
        val datalist=ArrayList<String>()
        db=openOrCreateDatabase("endsem.db", MODE_PRIVATE,null)
        val fetchQuery="Select name from person"
        val cursor=db?.rawQuery(fetchQuery,null)
        while(cursor!!.moveToNext())
        {
            val name=cursor.getString(0)
            datalist.add(name)
        }
        cursor.close()
        val adapter= ArrayAdapter(this,android.R.layout.simple_spinner_dropdown_item,datalist)
        spin.adapter=adapter

        var originaldatalist=datalist.toList()

        spin.onItemSelectedListener= object : AdapterView.OnItemSelectedListener{
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                if (!userHasInteracted) {
                    userHasInteracted = true
                    return
                }
                datalist.clear()
                datalist.addAll(originaldatalist)

                val selectedName = datalist[position]
                Toast.makeText(this@Page5, "Item selected is $selectedName", Toast.LENGTH_SHORT).show()
                val showQuery="Select food from person where name='$selectedName'"
                val cursor2=db.rawQuery(showQuery,null)

                while(cursor2!!.moveToNext())
                {
                    val food=cursor2.getString(0)
                    val msg="Name: $selectedName ,Food: $food"
                    datalist[position]=msg
                    adapter.notifyDataSetChanged()
                }
                cursor2.close()
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {
            }
        }

我尝试清理和重建项目、同步 Gradle 文件,甚至重新启动 Android Studio,但错误仍然存在。

除了解决此错误之外,我还在寻求有关在 Kotlin Android 应用程序中实现 CRUD 操作的指导。任何与 Kotlin 中的 CRUD 操作相关的建议、资源或示例将不胜感激。

android kotlin qwerty othello topaz-workbench
1个回答
0
投票

您可以在代码中查看以下不同的内容:

1.无线电组

<RadioGroup
            android:id="@+id/RG1"
            android:layout_width="204dp"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <RadioButton
                android:id="@+id/rb1"
                android:layout_width="89dp"
                android:layout_height="wrap_content"
                android:layout_marginEnd="16dp"
                android:text="True" />

            <RadioButton
                android:id="@+id/rb2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="False" />
        </RadioGroup>

2.通知和计算测验

class MainActivity : AppCompatActivity() {
companion object {
    private const val NOTIFICATION_CHANNEL_ID = "001"
    private const val POST_NOTIFICATIONS_REQUEST_CODE = 101
}

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val submitButton = findViewById<Button>(R.id.submit_button)
    submitButton.setOnClickListener {
        showAlertDialog()
    }
}
private var tempScore: Int = 0
private fun createNotificationChannel() {
    val name = "Results"
    val descriptionText = "Your Score is Good"
    val importance = NotificationManager.IMPORTANCE_DEFAULT
    val channel = NotificationChannel(NOTIFICATION_CHANNEL_ID, name, importance).apply {
        description = descriptionText
    }
    val notificationManager: NotificationManager =
        getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    notificationManager.createNotificationChannel(channel)
}

private fun checkPermissionsAndShowNotification(score: Int) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.POST_NOTIFICATIONS), POST_NOTIFICATIONS_REQUEST_CODE)
        } else {
            showNotification(score)
        }
    } else {
        showNotification(score)
    }
}
@SuppressLint("MissingPermission")
private fun showNotification(score: Int) {
    createNotificationChannel() // Ensure the channel is created before showing a notification
    val builder = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
        .setSmallIcon(R.drawable.images) // Ensure you have a drawable named `images` in your drawable resources
        .setContentTitle("Quiz Result")
        .setContentText("Your score is $score") // Incorporate the score into the notification text
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
    with(NotificationManagerCompat.from(this)) {
        notify(1, builder.build()) // The first parameter is a unique ID for the notification
    }
}

private fun showAlertDialog() {
    AlertDialog.Builder(this)
        .setTitle("Submit Confirmation")
        .setMessage("Are you sure you want to submit?")
        .setPositiveButton("Yes") { dialog, which ->
            dialog.dismiss()
            Toast.makeText(this, "Submission Confirmed", Toast.LENGTH_SHORT).show()
            calcres()

        }
        .setNegativeButton("No") { dialog, which ->
            dialog.dismiss()
        }
        .show()
}

private fun calcres() {
    val radioGroupIds = arrayOf(
        R.id.RG1, R.id.RG2, R.id.RG3, R.id.RG4, R.id.RG5,
        R.id.RG6, R.id.RG7, R.id.RG8, R.id.RG9, R.id.RG10,
        R.id.RG11, R.id.RG12 // Add IDs for the new RadioGroups
    )

    val correctans = mutableListOf(
        "True", "False", "True", "False", "True",
        "False", "True", "False", "True", "False",
        "True", "False" // Add the correct answers for the new questions
    )
    val urans = mutableListOf<String>()
    var score = 0

    radioGroupIds.forEachIndexed { index, radioGroupId ->
        val radioGroup = findViewById<RadioGroup>(radioGroupId)
        val selectedRadioButtonId = radioGroup.checkedRadioButtonId
        if (selectedRadioButtonId != -1) {
            val radioButton = findViewById<RadioButton>(selectedRadioButtonId)
            val selectedText = radioButton.text.toString()
            urans.add(selectedText)
            if (selectedText == correctans[index]) {
                score++
            }
        } else {
            urans.add("Not Answered")
        }
    }

    tempScore = score
    checkPermissionsAndShowNotification(score)
    val intent = Intent(this, MainActivity2::class.java).apply {
        putExtra("score", score)
        putStringArrayListExtra("ans", ArrayList(urans))
    }
    startActivity(intent)
}

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    if (requestCode == POST_NOTIFICATIONS_REQUEST_CODE && grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        showNotification(tempScore) // Use tempScore here
    } else {
        Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show()
    }
}

}

下一页代码

val getans:ArrayList<String>?=intent.getStringArrayListExtra("ans")
    val answersText = getans?.joinToString(separator = "\n") ?: "No answers provided"
    val score=intent.getIntExtra("score",0)

    val textid=findViewById<TextView>(R.id.textView2)
    textid.text="Your Score is $score/12 "

    val textid2=findViewById<TextView>(R.id.textView3)
    textid2.text="Your answers are: $answersText \n"

3.复选框、旋转器、单选框的基本代码

val countries= arrayOf("Select Country", "USA", "Canada", "India", "Australia")
    spin.adapter=ArrayAdapter(this,android.R.layout.simple_spinner_dropdown_item,countries)

    submit.setOnClickListener {
        val radioID=sex_rg.checkedRadioButtonId
        val rb=findViewById<RadioButton>(radioID)
        val gender=rb.text.toString()
        val name1=name.text.toString()
        val terms=chkbox.isChecked
        val coun=spin.selectedItem.toString()

4.FOR /While 循环

for (i in 1..10) {
println("Iteration: $i")}
val text = "Hello, World!"
for (char in text) {
    println(char)
}

val arrayOfZeros = Array(5) { 0 }

// Using a for loop to populate the array
for (index in arrayOfZeros.indices) {
    arrayOfZeros[index] = index * 2
}

// Print the array to verify the contents
println(arrayOfZeros.contentToString())

// Functional-style forEach loop
numbers.forEach { number ->
    println("Number: $number")
}

// forEachIndexed provides both the index and the value
fruits.forEachIndexed { index, fruit ->
    println("Fruit at index $index is $fruit")
}

while (index < fruits.size) {
    println("Fruit: ${fruits[index]}")
    index++  // Increment the index
}

5.Array/ArrayList/可变列表

   val emptyIntArray: Array<Int> = arrayOf()
   val anotherEmptyArrayList = ArrayList<String>()

   val emptyMutableList: MutableList<String> = mutableListOf()
   

6.如何从函数返回多个值

fun fetchEmployeeDetails(): List<Any> {
    // Example values, normally fetched from a database
    val name = "John Doe"
    val gender = "Male"
    val age = 30
    val salary = 58000.0

    // Return a list containing all details
    return listOf(name, gender, age, salary)
}

fun main() {
    val employeeDetails = fetchEmployeeDetails()

    // Accessing elements in the list
    val name = employeeDetails[0] as String
    val gender = employeeDetails[1] as String
    val age = employeeDetails[2] as Int
    val salary = employeeDetails[3] as Double
© www.soinside.com 2019 - 2024. All rights reserved.