Skip to content

以下是 Android 开发中常用控件的使用方法和最佳实践,结合 Kotlin 代码示例现代开发规范


1. TextView(文本显示)

基础用法

xml
<!-- XML 布局 -->
<TextView
    android:id="@+id/tv_title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World"
    android:textColor="#333"
    android:textSize="18sp"
    android:maxLines="2"
    android:ellipsize="end" />

动态修改文本

kotlin
// Kotlin 代码
val tvTitle: TextView = findViewById(R.id.tv_title)
tvTitle.text = "New Text"
tvTitle.setTextColor(ContextCompat.getColor(this, R.color.red))

最佳实践

  • 使用 strings.xml 管理文本资源:
    xml
    <string name="app_name">My App</string>
    kotlin
    tvTitle.setText(R.string.app_name)

2. Button(按钮)

基础点击事件

xml
<Button
    android:id="@+id/btn_submit"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Submit" />
kotlin
val btnSubmit: Button = findViewById(R.id.btn_submit)
btnSubmit.setOnClickListener {
    // 处理点击事件
    showToast("Button clicked!")
}

防重复点击

kotlin
// 扩展函数:防止快速点击(500ms 间隔)
fun View.setOnSingleClickListener(interval: Long = 500, action: () -> Unit) {
    var lastClickTime = 0L
    setOnClickListener {
        val currentTime = System.currentTimeMillis()
        if (currentTime - lastClickTime > interval) {
            lastClickTime = currentTime
            action()
        }
    }
}

// 使用
btnSubmit.setOnSingleClickListener {
    submitForm()
}

3. EditText(输入框)

基础输入监听

xml
<EditText
    android:id="@+id/et_username"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="请输入用户名"
    android:inputType="text" />
kotlin
val etUsername: EditText = findViewById(R.id.et_username)
etUsername.addTextChangedListener(object : TextWatcher {
    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
    override fun afterTextChanged(s: Editable?) {
        val input = s?.toString() ?: ""
        // 实时校验输入
        if (input.length < 6) {
            etUsername.error = "用户名至少6位"
        }
    }
})

输入类型控制

xml
<!-- 密码输入 -->
<EditText
    android:inputType="textPassword"
    android:imeOptions="actionDone" />

<!-- 邮箱输入 -->
<EditText
    android:inputType="textEmailAddress" />

4. RecyclerView(列表)

基础实现

xml
<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/rv_list"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layoutManager="LinearLayoutManager" />

适配器与 ViewHolder

kotlin
class MyAdapter(private val items: List<String>) : 
    RecyclerView.Adapter<MyAdapter.ViewHolder>() {

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val tvItem: TextView = itemView.findViewById(R.id.tv_item)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_list, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.tvItem.text = items[position]
        holder.itemView.setOnClickListener { 
            // 点击事件
        }
    }

    override fun getItemCount() = items.size
}

// 使用
val rvList: RecyclerView = findViewById(R.id.rv_list)
rvList.adapter = MyAdapter(listOf("Item 1", "Item 2", "Item 3"))

最佳实践

  • 使用 ListAdapterDiffUtil 优化数据更新。
  • 添加分割线:
    kotlin
    rvList.addItemDecoration(
        DividerItemDecoration(this, DividerItemDecoration.VERTICAL)
    )

5. ImageView(图片显示)

加载本地资源

xml
<ImageView
    android:id="@+id/iv_avatar"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:scaleType="centerCrop"
    android:src="@drawable/ic_default_avatar" />

加载网络图片(使用 Glide)

kotlin
// 添加依赖:implementation 'com.github.bumptech.glide:glide:4.12.0'
Glide.with(this)
    .load("https://example.com/image.jpg")
    .placeholder(R.drawable.ic_placeholder)
    .error(R.drawable.ic_error)
    .circleCrop() // 圆形裁剪
    .into(ivAvatar)

6. CheckBox 和 RadioButton(选择控件)

CheckBox

xml
<CheckBox
    android:id="@+id/cb_agree"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="同意协议" />
kotlin
val cbAgree: CheckBox = findViewById(R.id.cb_agree)
cbAgree.setOnCheckedChangeListener { _, isChecked ->
    btnSubmit.isEnabled = isChecked
}

RadioGroup

xml
<RadioGroup
    android:id="@+id/rg_gender"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <RadioButton
        android:id="@+id/rb_male"
        android:text="男" />
    <RadioButton
        android:id="@+id/rb_female"
        android:text="女" />
</RadioGroup>
kotlin
val rgGender: RadioGroup = findViewById(R.id.rg_gender)
rgGender.setOnCheckedChangeListener { group, checkedId ->
    when (checkedId) {
        R.id.rb_male -> { /* 处理选择 */ }
        R.id.rb_female -> { /* 处理选择 */ }
    }
}

7. ProgressBar(进度条)

圆形加载指示器

xml
<ProgressBar
    android:id="@+id/pb_loading"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:visibility="gone" />

代码控制

kotlin
fun showLoading() {
    pbLoading.visibility = View.VISIBLE
}

fun hideLoading() {
    pbLoading.visibility = View.GONE
}

8. 其他实用控件

控件用途关键特性
Switch开关按钮isChecked 属性监听状态变化
Spinner下拉选择框配合 ArrayAdapter 使用
WebView显示网页内容需处理生命周期和权限
CardView卡片式布局容器圆角、阴影效果
ViewPager2滑动翻页替代旧版 ViewPager,支持垂直滑动

最佳实践总结

  1. 使用 ViewBinding 替代 findViewById

    kotlin
    // 在模块级 build.gradle 中启用
    android {
        buildFeatures {
            viewBinding true
        }
    }
    
    // 在 Activity 中使用
    private lateinit var binding: ActivityMainBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.tvTitle.text = "Hello"
    }
  2. 样式统一:通过 styles.xmlthemes.xml 统一控件外观。

  3. 性能优化

    • 避免在 RecyclerViewonBindViewHolder 中执行耗时操作。
    • 使用 ConstraintLayout 减少布局嵌套。

通过掌握这些控件的使用方法,可以高效构建 Android 应用的 UI 界面。