简体   繁体   中英

Remove LinearLayout with a button, which is inside this LinearLayout

I've created a custom linear layout within android studio. 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. Here is my layout:

截屏

And as you can see the button "DELETE HERE" should remove the 3 items, time, weekday and the button itself.

This is my class and here

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? I tried using alarmCards.removeView(this) within btnDelete.setOnClickListener() but It crashes. :(

Thank you!!

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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