Home > front end >  How to make a ListView in a Fragment display my data (Android)?
How to make a ListView in a Fragment display my data (Android)?

Time:07-16

I'm working on my Android app and have a Fragment FragmentBlank with TextView messages_list in it. In the FragmentBlank.kt I wrote these 5 lines:

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    val view = inflater.inflate(R.layout.fragment_blank, container, false)
    val listOfMessages = view.findViewById<ListView>(R.id.messages_list)
    val values = arrayOf("Android", "iPhone", "WindowsMobile", "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X", "Linux", "OS/2")
    val adapter: ArrayAdapter<String> = ArrayAdapter<String>(view.context, android.R.layout.simple_list_item_1, values)
    listOfMessages.setAdapter(adapter)

    return inflater.inflate(R.layout.fragment_blank, container, false)
}

But after I run my application I see that messages_list is empty. How could I fix it?

CodePudding user response:

In this line, you are throwing away everything you already created above it by inflating a new view and returning that:

return inflater.inflate(R.layout.fragment_blank, container, false)

You should return the view you already created:

return view

But I think it's cleaner to pass your layout ID to the fragment constructor, and override onViewCreated() instead of onCreateView(), like this:

class MyFragment: Fragment(R.layout.fragment_blank) {

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        val listOfMessages = view.findViewById<ListView>(R.id.messages_list)
        val values = arrayOf("Android", "iPhone", "WindowsMobile", "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X", "Linux", "OS/2")
        val adapter: ArrayAdapter<String> = ArrayAdapter<String>(view.context, android.R.layout.simple_list_item_1, values)
        listOfMessages.setAdapter(adapter)
    }
}
  • Related