You have two options here:
1) Don't embed the button in your layout file. Generate the button on the fly and add it to your view.
Example:
fun createButton(context:Context):Button{
val btn = Button(context)
btn.text = "Magic"
btn.setOnClickListener { Toast.makeText(context, "You clicked me!", Toast.LENGTH_SHORT).show() }
return btn
}
Where you want to add the button:
val parent = findViewById<LinearLayout>(R.id.parent)
btnAdd.setOnClickListener{
val btn = createButton(this)
parent.addView(btn)
}
btnRemove.setOnClickListener{
parent.removeViewAt(0)
}
2) Second approach, if you want to have a layout file, is create a custom layout with the button like this:
button_layout.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="@+id/btnTest"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Magic" />
</LinearLayout>
In your activity, have a parent layout (any layout of your choice) :
<LinearLayout
android:id="@+id/parent"
android:layout_width="409dp"
android:layout_height="354dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.254"/>
I have used linear layout for this example.
Now in the activity, inflate the custom layout and add it your view :
val parent = findViewById<LinearLayout>(R.id.parent)
btnAdd.setOnClickListener{
val btnView = LayoutInflater.from(this).inflate(R.layout.button_layout, null)
btnView.findViewById<Button>(R.id.btnTest).text = "Some other text"
val lp = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)
parent.addView(btnView, lp)
}
btnRemove.setOnClickListener{
parent.removeViewAt(0)
}
In the above example, I have two buttons, add and remove which adds the custom layout & removes it respectively.
The advantage of this is, after inflating it, based on condition, you can do like:
btnView.findViewById<Button>(R.id.btnTest).text = "Some other text"
and change only the part you need to change (eg. text/image) and keep the rest of the styles same.
This holds true for any button (normal or image button).
Hope this example helps, if you have any other query, do tell.
Regards
Priyabrata