Home > Enterprise >  Create a button programmatically in a fragment using Kotlin
Create a button programmatically in a fragment using Kotlin

Time:04-05

I wish to generate a column of buttons inside a fragment in Kotlin from a database. For now I tried with just one button, but I cannot seem to do it without hardcoding it in the XML file. Here is my code so far:

class NotesFragment() : Fragment() {


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

        val view: View = inflater!!.inflate(R.layout.fragment_notes, container, false)
        //val root : ViewGroup = inflater.inflate(R.layout.fragment_notes, null) as ViewGroup

        val button_Id: Int = 1111
        val button = Button((activity as MainActivity?)!!)
        button.setText("Button 4 added dynamically")
        button.setLayoutParams(ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT))
        button.setId(button_Id)
        button.x = 250f
        button.y = 500f
        button.setOnClickListener(this)
        view.add(button)

        return view
    }
}

I know I should probably look for the layout somewhere in this and do an addView with it... What is the next step?

CodePudding user response:

I did it like this

view.rootView.findViewById<RelativeLayout>(R.id.button_container).addView(button)

CodePudding user response:

You can create the button by calling the constructor.

private fun createButtonDynamically() {
// creating the button
val dynamicButton = Button(this)
// setting layout_width and layout_height using layout parameters
dynamicButton.layoutParams = LinearLayout.LayoutParams(
    LinearLayout.LayoutParams.WRAP_CONTENT,
    LinearLayout.LayoutParams.WRAP_CONTENT
)
dynamicButton.text = "Dynamic Button"
dynamicButton.setBackgroundColor(Color.GREEN)
// add Button to LinearLayout
mainLayout.addView(dynamicButton)

}

  • Related