Add a ListView in Fragment without using ListFragment. Add a listview in fragment.

Source: Internet
Author: User

Add a ListView in Fragment without using ListFragment. Add a listview in fragment.

The initial idea was to combine Fragment and ViewPager,

Then, in a whim, The ListView is added to the first Fragment,

According to the suggestions on the internet, extends has ListFragment, followed by various errors.

After reading it carefully, it turns out to be MainActivity here:

1 // construct the adapter 2 List <Fragment> fragments = new ArrayList <Fragment> (); 3 fragments. add (new Fragment1 (); 4 fragments. add (new Fragment2 (); 5 fragments. add (new Fragment3 (); 6 FPAdapter adapter = new FPAdapter (getSupportFragmentManager (), fragments );

Because yes

List <Fragment>

Fragment1 will naturally report an error when using ListFragment.

Modify the code in Fragment1 and add the ListView as follows:

 1 public class Fragment1 extends Fragment { 2  3     private ListView listView; 4  5  6     public View onCreateView(LayoutInflater inflater, ViewGroup container, 7                              Bundle savedInstanceState) { 8         // TODO Auto-generated method stub 9         View view= inflater.inflate(R.layout.layout1, container, false);10         listView = (ListView)view.findViewById(R.id.lv);11         ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(),12                 android.R.layout.simple_list_item_1,getData());13         listView.setAdapter(arrayAdapter);14 15         return view;16     }17 18     private List<String> getData(){19         List<String> data = new ArrayList<String>();20         for(int i = 0;i <20;i++) {21             data.add(i+"");22         }23         return data;24     }25 }

Where

Android. R. layout. simple_list_item_1

Is built-in and does not need to be defined.

 

In this way, the ListView will be displayed normally.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.