提升Android开发效率的15个实用代码片段

在Android开发过程中,掌握一些实用代码片段可以显著提升开发效率。以下整理了15个常用的Android代码片段,帮助开发者简化代码、优化性能:

  1. 检查网络连接状态:
// 检查网络连接状态
fun isNetworkConnected(context: Context): Boolean {
    val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    val activeNetwork = connectivityManager.activeNetworkInfo
    return activeNetwork?.isConnectedOrConnecting == true
}
  1. 获取屏幕尺寸:
// 获取屏幕宽度和高度(以像素为单位)
val displayMetrics = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(displayMetrics)
val screenWidth = displayMetrics.widthPixels
val screenHeight = displayMetrics.heightPixels
  1. 隐藏软键盘:
// 隐藏软键盘
val inputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
  1. 显示软键盘:
// 显示软键盘
val inputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
  1. 启动 Activity:
// 启动 Activity
val intent = Intent(this, TargetActivity::class.java)
startActivity(intent)
  1. 传递数据到 Activity:
// 传递数据到 Activity
val intent = Intent(this, TargetActivity::class.java)
intent.putExtra("key", "value")
startActivity(intent)
  1. 从 Activity 接收数据:
// 从 Activity 接收数据
val value = intent.getStringExtra("key")
  1. 创建 Toast 消息:
// 创建 Toast 消息
Toast.makeText(this, "消息内容", Toast.LENGTH_SHORT).show()
  1. 读取 SharedPreferences:
// 读取 SharedPreferences
val sharedPreferences = getSharedPreferences("preferences_name", Context.MODE_PRIVATE)
val value = sharedPreferences.getString("key", "default_value")
  1. 写入 SharedPreferences:
// 写入 SharedPreferences
val sharedPreferences = getSharedPreferences("preferences_name", Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
editor.putString("key", "value")
editor.apply()
  1. 设置 View 的可见性:
// 设置 View 可见
view.visibility = View.VISIBLE

// 设置 View 不可见
view.visibility = View.INVISIBLE

// 设置 View 消失
view.visibility = View.GONE
  1. 设置 ImageView 图片资源:
// 设置 ImageView 图片资源
imageView.setImageResource(R.drawable.image)
  1. 设置 TextView 文本颜色:
// 设置 TextView 文本颜色
textView.setTextColor(ContextCompat.getColor(this, R.color.color_name))
  1. 格式化日期:
// 格式化日期
val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
val formattedDate = simpleDateFormat.format(Date())
  1. 启动后台线程:
// 启动后台线程
Thread {
    // 后台任务
}.start()

注意: 以上代码片段仅供参考,实际应用中可能需要根据具体情况进行调整。

docx 文件大小:16.4KB