📜  Kotlin 中的复选框

📅  最后修改于: 2022-05-13 01:55:23.609000             🧑  作者: Mango

Kotlin 中的复选框

CheckBox 是 Android 中的一种特殊按钮,具有选中或未选中两种状态。 Checkbox 是在 Android 中使用的一个非常常见的小部件,一个很好的例子是应用程序的任何类型的登录活动中的“记住我”选项,它要求用户激活或停用该服务。 CheckBox 小部件还有许多其他用途,例如为用户提供选项列表以供选择,并且这些选项是互斥的,即用户可以选择多个选项。 CheckBox 的这一特性使其成为在 android 中设计多项选择题应用程序或调查应用程序时使用的更好选择。

Kotlin 中 CheckBox 类的类层次结构

Kotlin中CheckBox类的类层次图

CheckBox 小部件的 XML 属性

XML AttributesDescription
android:idUsed to uniquely identify a CheckBox
android:checkedTo set the default state of a CheckBox as checked or unchechek
android:backgroundTo set the background color of a CheckBox
android:textUsed to store a text inside the CheckBox
android:fontFamilyTo set the font of the text of the CheckBox
android:textSizeTo set the CheckBox text size
android:layout_widthTo set the CheckBox width
android:layout_heightTo set the CheckBox height
android:gravityUsed to adjust the CheckBox text alignment
android:paddingUsed to adjust the left, right, top and bottom padding of the CheckBox

例子

此示例演示了设计一个包含 5 个 CheckBox 和一个附加提交按钮的活动所涉及的步骤,以显示已记录用户响应的 toast 消息。

创建新项目

  1. 单击文件,然后单击新建 => 新建项目。
  2. 为项目模板选择“Empty Activity”。
  3. 选择语言为 Kotlin。
  4. 根据您的需要选择最低 SDK。

打开 activity_main.xml 文件

下面是添加 5 个 CheckBox 的activity_main.xml文件的代码。还添加了一个普通的“提交”按钮,以显示已记录用户响应的 toast 消息。



  
    
  
    
  
        
  
        
  
        
  
        
  
        
    
  
    

打开 MainActivity.kt 文件

下面是MainActivity.kt文件的代码,用于访问 kotlin 文件中的 CheckBox 小部件,并在用户单击提交按钮时显示正确的消息。

package com.example.checkboxinkotlin
  
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
  
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        // Assigning id of the submit button
        val button : Button = findViewById(R.id.submitButton)
  
        // Actions to be performed
        // when Submit button is clicked
        button.setOnClickListener{
  
            // Display toast message
            Toast.makeText(applicationContext,
                "Your response has been recorded", Toast.LENGTH_LONG).show()
        }
    }
}

修改字符串.xml 文件

该文件中列出了活动中使用的所有字符串,从文本视图到复选框文本。


    CheckBox in Kotlin
    Services provided by GeeksforGeeks
    Coding contests
    Civil Engineering Courses
    Coding Contests
    Computer Science Courses
    Company specific coding questions
    Download movies
    SUBMIT

AndroidManifest.xml 文件

下面是AndroidManifest.xml文件的代码。



  
    
        
            
                
  
                
            
        
    
  

输出

CheckBox 活动截图