我有一个自定义的文本视图,它放在LinearLayout内部
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools">
<TextView
android:id="@+id/timerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:maxLines="2"
android:ellipsize="end"
tools:text="Only on 22 of July, 2019"
android:textColor="@color/white" />
</LinearLayout>
和具有一些逻辑的自定义计时器视图
class CustomTimerView(context: Context, attributeSet: AttributeSet) : LinearLayout(context, attributeSet) {
private var textView: TextView
init {
LinearLayout.inflate(context, R.layout.customTimer_layout, this)
textView = findViewById(R.id.timerView)
}
fun setDates(ob: Promo) {
val startDate = getStartDate(ob)
val endDate = getEndDate(ob)
if (startDate.get(Calendar.MONTH) != endDate.get(Calendar.MONTH)) {
textView.text = getInDifferentMonths(context!!, ob)
} else {
if (startDate.get(Calendar.DAY_OF_MONTH) == endDate.get(Calendar.DAY_OF_MONTH)) {
textView.text = getOnlyOneDay(context!!, ob)
} else {
textView.text = getInOneMonth(context!!, ob)
}
}
}
}
显然,LinearLayout是无用的。但是,如何在不将 textView 数据移动到代码和其他布局中的子级的情况下删除它呢?
您可以将线性布局替换为文本视图:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:maxLines="2"
android:ellipsize="end"
tools:text="Only on 22 of July, 2019"
android:textColor="@color/white"
/>
关于这门课,我不知道我理解是否正确,但我会猜测一下:
class CustomTimerView(context: Context, attributeSet: AttributeSet) : TextView(context, attributeSet) {
init {
TextView.inflate(context, R.layout.custom_timer_layout, null)
}
fun setDates(ob: Promo) {
val startDate = getStartDate(ob)
val endDate = getEndDate(ob)
if (startDate.get(Calendar.MONTH) != endDate.get(Calendar.MONTH)) {
this.text = getInDifferentMonths(context!!, ob)
} else {
if (startDate.get(Calendar.DAY_OF_MONTH) == endDate.get(Calendar.DAY_OF_MONTH)) {
this.text = getOnlyOneDay(context!!, ob)
} else {
this.text = getInOneMonth(context!!, ob)
}
}
}
}