Android list in fragment for viewpager

2019-08-05 12:40发布

问题:

I have a viewpager set up and fragments for each page but can't figure out how to show a list inside one of the fragments everything i've tried has forced closed so here's what i'm back to right now

public class Extras extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View V = inflater.inflate(R.layout.extras, null, false);
        return V;
    }
}

Any help on how i could turn that into a simple list would be greatly appreciated

===Edit===

Final Result

public class Extras extends ListFragment { 

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        this.getListView().setTextFilterEnabled(true);
        this.setListAdapter(new ArrayAdapter<String>(getActivity(), R.layout.row, items));
        this.setEmptyText(getString(R.string.loading));
    }
    static final String[] items = new String[] {"Item 1", "Item 2", "Item 3", "Item 4", "Item 5"};

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
     super.onListItemClick(l, v, position, id);
        Toast.makeText(getActivity(), l.getItemAtPosition(position).toString(), Toast.LENGTH_LONG).show();
    }
}

回答1:

you can use ListFragment

public class ExtraListFragment extends ListFragment { 

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        this.getListView().setTextFilterEnabled(true);

        this.setListAdapter(adapter); // your list adapter
        this.setEmptyText(getString(R.string.loading));
    }
}