2018/11/18

Android, Add Button Dynamically

Kotlin, adding a button dynamically by code to a Fragment.

class Gu1Fragment : Fragment() {
// ...
// dynamically add a button to the fragment
// beware it is in onViewCreated, should NOT be in onCreateView
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val btn :Button = Button(requireContext())
btn.setText("Manually added by code")
// a linear layout in the framgment layout xml
val layout: LinearLayout = view.findViewById(R.id.gu_layout)
layout.addView(btn)
}
}
view raw Gu1Fragment.kt hosted with ❤ by GitHub

No comments:

Post a Comment

Post Code on Blogger

Simplest way to post code to blogger for me: <pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black;overflow-x:...