从自定义 textView 中删除线性布局

Remove linear layout from custom textView

我有一个自定义的 textView,它放在 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>

和具有一定逻辑的 CustomTimerView

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 数据移动到代码和其他布局中的子级的情况下删除它?

您可以用 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,不知道我理解的对不对,猜猜看:

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)
            }
        }
    }
}