0

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?

4
  • 2
    you can directly get rootview from fragment xml and add into it using addView Commented Apr 4, 2022 at 4:53
  • 1
    You should create xml file for button and then add then whenever you want in your fragment. Commented Apr 4, 2022 at 5:01
  • How? Like this? view.rootView.addView(button) Commented Apr 4, 2022 at 7:39
  • 1
    Yes and don't forget to specify a different button id for each btn, if you will inflate from xml. Just call button.setId(View.generateViewId()) Commented Apr 4, 2022 at 8:21

1 Answer 1

0

I did it like this

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.