Android ListView in Fragment

前端 未结 2 1532
情深已故
情深已故 2020-12-03 15:26

I am trying to create a list of items which contains an image and some description for the image in each individual. After which, the list will be place in a fragment<

相关标签:
2条回答
  • 2020-12-03 15:48

    Here's a code snippet to help you display ListView in a fragment.:

    public class MessagesFragment extends ListFragment {
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_messages, container,
                false);
    
        String[] values = new String[] { "Message1", "Message2", "Message3" };
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
            android.R.layout.simple_list_item_1, values);
        setListAdapter(adapter);
        return rootView;
    }
    }
    

    And, this is how the xml would look like:

    <ListView
      android:id="@android:id/list"
      android:layout_width="match_parent"
      android:layout_height="wrap_content" >
    </ListView>
    

    If you do not use 'list' as ID or do not include a ListView into your layout, the application crashes once you try to display the activity or the fragment.

    Reference: http://www.vogella.com/tutorials/AndroidListView/article.html#listfragments

    0 讨论(0)
  • 2020-12-03 15:52

    It seems like your Fragment should subclass ListFragment (not ListActivity). onCreateView() from ListFragment will return a ListView you can then populate.

    Here's more information on populating lists from the developer guide: Hello, ListView

    0 讨论(0)
提交回复
热议问题