提升Android开发效率的15个实用代码片段
在Android开发过程中,掌握一些实用代码片段可以显著提升开发效率。以下整理了15个常用的Android代码片段,帮助开发者简化代码、优化性能:
- 检查网络连接状态:
// 检查网络连接状态
fun isNetworkConnected(context: Context): Boolean {
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetwork = connectivityManager.activeNetworkInfo
return activeNetwork?.isConnectedOrConnecting == true
}
- 获取屏幕尺寸:
// 获取屏幕宽度和高度(以像素为单位)
val displayMetrics = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(displayMetrics)
val screenWidth = displayMetrics.widthPixels
val screenHeight = displayMetrics.heightPixels
- 隐藏软键盘:
// 隐藏软键盘
val inputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
- 显示软键盘:
// 显示软键盘
val inputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
- 启动 Activity:
// 启动 Activity
val intent = Intent(this, TargetActivity::class.java)
startActivity(intent)
- 传递数据到 Activity:
// 传递数据到 Activity
val intent = Intent(this, TargetActivity::class.java)
intent.putExtra("key", "value")
startActivity(intent)
- 从 Activity 接收数据:
// 从 Activity 接收数据
val value = intent.getStringExtra("key")
- 创建 Toast 消息:
// 创建 Toast 消息
Toast.makeText(this, "消息内容", Toast.LENGTH_SHORT).show()
- 读取 SharedPreferences:
// 读取 SharedPreferences
val sharedPreferences = getSharedPreferences("preferences_name", Context.MODE_PRIVATE)
val value = sharedPreferences.getString("key", "default_value")
- 写入 SharedPreferences:
// 写入 SharedPreferences
val sharedPreferences = getSharedPreferences("preferences_name", Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
editor.putString("key", "value")
editor.apply()
- 设置 View 的可见性:
// 设置 View 可见
view.visibility = View.VISIBLE
// 设置 View 不可见
view.visibility = View.INVISIBLE
// 设置 View 消失
view.visibility = View.GONE
- 设置 ImageView 图片资源:
// 设置 ImageView 图片资源
imageView.setImageResource(R.drawable.image)
- 设置 TextView 文本颜色:
// 设置 TextView 文本颜色
textView.setTextColor(ContextCompat.getColor(this, R.color.color_name))
- 格式化日期:
// 格式化日期
val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
val formattedDate = simpleDateFormat.format(Date())
- 启动后台线程:
// 启动后台线程
Thread {
// 后台任务
}.start()
注意: 以上代码片段仅供参考,实际应用中可能需要根据具体情况进行调整。
16.4KB
文件大小:
评论区