Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set list view adapter in a fragment in android

I want a custom row, so I am using a List View in an xml and inflating into a fragment. I am very confused of how to set the adapter for the list View. I created a new adapter which extends Base Adapter. In the getView method, I really don't know what context to pass while inflating the row.xml layout. How do I set the adapter for the list view and where?

public class ResultsFragment extends Fragment{


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.results_layout, container, false);
        listView = (ListView)v.findViewById(R.id.results);
        return v;
    }

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


        loadPage(dataBean.getWhat(), dataBean.getWhere(), dataBean.getPageStart());

        //resultsAdapter.setRssData(rssData);
        //setListAdapter(resultsAdapter);
    }

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        Context context = getActivity().getApplicationContext();
        resultsAdapter = new ResultsAdapter(context);
    }





    /**
     * Set List Adapter
     */
    private void setAdapter(){
        if(listView.getAdapter() == null){
            listView.setAdapter(resultsAdapter);
        }
        else{
            resultsAdapter.notifyDataSetChanged();
        }
    }


}
like image 918
dcanh121 Avatar asked Oct 01 '11 05:10

dcanh121


2 Answers

You must extend Listfragment (instead of Fragment), and using its ListFragment.setListAdapter to set your adapter. In the adapter getView() inflate your row.. that s all

like image 164
Blackbelt Avatar answered Nov 04 '22 11:11

Blackbelt


If you do not want to change your extended class, you should use listview.setAdapter(...) method. As you see in my example :

ListView productList= (ListView) getActivity().findViewById(R.id.product_list);


    SampleAdapter adapter = new SampleAdapter(getActivity());


    adapter.add(new SampleItem(
            "Sunny LCD TV 2\"  SN022L66-T1 Full HD",
            R.drawable.product_sample_pic);


    productList.setAdapter(adapter);
like image 10
alicanbatur Avatar answered Nov 04 '22 10:11

alicanbatur