目标
熟悉注解的基本使用方法.
本文介绍为普通activity增加一个通用的顶部栏.
主要代码
定义注解
@kotlin.annotation.Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.ANNOTATION_CLASS, AnnotationTarget.CLASS)
annotation class TitleBar(val value: String = "")
增加注解处理类
open class BaseActivity : AppCompatActivity() {
override fun setContentView(layoutResID: Int) {
val titleBarAnnotation = javaClass.getAnnotation(TitleBar::class.java)
if (titleBarAnnotation != null) {
var linearLayout = LinearLayout(this)
linearLayout.orientation = LinearLayout.VERTICAL
addTitleBar(titleBarAnnotation, linearLayout)
addOriginalView(layoutResID, linearLayout)
super.setContentView(linearLayout)
} else {
super.setContentView(layoutResID)
}
}
private fun addOriginalView(layoutResID: Int, linearLayout: LinearLayout) {
var params = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT
)
var contentView = LayoutInflater.from(this).inflate(layoutResID, null, false)
linearLayout.addView(contentView, params)
}
private fun addTitleBar(titleBarAnnotation: TitleBar, linearLayout: LinearLayout) {
val textView = TextView(this)
titleBarAnnotation.value.let { textView.text = it }
linearLayout.addView(textView)
}
}
使用注解
@TitleBar(value = "顶部栏")
class MainActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
效果图:
完整源代码