简体   繁体   English

使用按钮删除 LinearLayout,该按钮位于此 LinearLayout 内

[英]Remove LinearLayout with a button, which is inside this LinearLayout

I've created a custom linear layout within android studio.我在 android 工作室中创建了一个自定义线性布局。 This layout gets inflated into another vertical layout programatically.此布局以编程方式膨胀为另一个垂直布局。 Now I want to map a button inside this layout, which can delete the whole object.现在我想在这个布局里面给map一个按钮,里面可以删除整个object。 Here is my layout:这是我的布局:

截屏

And as you can see the button "DELETE HERE" should remove the 3 items, time, weekday and the button itself.如您所见,“在此处删除”按钮应删除 3 个项目,时间、工作日和按钮本身。

This is my class and here这是我的 class 和这里

class AlarmCard @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyle: Int = 0,
    defStyleRes: Int = 0,
    ) : LinearLayout(context, attrs, defStyle, defStyleRes) {

    init {
        LayoutInflater.from(context)
            .inflate(R.layout.alarmcard, this, true)

        btnDelete.setOnClickListener(){
           **/* Call destructor or remove view !?!*/**
        }
    }
}

which get added to the linear layout with:它被添加到线性布局中:

 val monday = AlarmCard(this)
 alarmCards.addView(monday)

The problem is for me how can I delete the object with a button?问题是我如何用按钮删除 object? I tried using alarmCards.removeView(this) within btnDelete.setOnClickListener() but It crashes.我尝试在 btnDelete.setOnClickListener() 中使用 alarmCards.removeView(this) 但它崩溃了。 :( :(

Thank you!!谢谢!!

Try this:尝试这个:

btnDelete.setOnClickListener {
    (getParent() as? ViewGroup)?.removeView(this@AlarmCard)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM