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

时间:2019-04-18 16:17:08

标签: android

我有一个自定义的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数据移动到其他布局中的代码和子布局的情况下删除它?

1 个答案:

答案 0 :(得分:2)

您可以将线性布局替换为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)
            }
        }
    }
}