Android BaseAdapter with Fragment

故事扮演 提交于 2019-12-05 07:24:42

Change

lv.setAdapter(new VcAdapter (this));

to

lv.setAdapter(new VcAdapter(getActivity()));

You need to pass activity context.

getActivity()

Return the Activity this fragment is currently associated with.

you also need to change this

@Override
    public long getItemId(int i) {
        // TODO Auto-generated method stub
        return 0;
    }

to

@Override
    public long getItemId(int i) {
        // TODO Auto-generated method stub
        return i;
    }

Your fragment list is probably not be getting populated because you are not passing the correct id into your fragment layout file.

In your fragment layout file, you should use

android:id="@android:id/list"

And NOT

android:id="+@id/list"

Trying to do it manually with the second option will work for Activities, but not for Fragments.

Therefore, you also have to extend a ListFragment instead of a Fragment, so that way BaseAdapter can figure out that you do in fact have a ListView within your fragment that it can set to the custom adapter. This also eliminates the need for you to explicitly define your ListView, meaning that you can safely remove the line where you retrieve it and still allow the fragment to generate its appropriate view.

Although, you will need to call setListAdapter(new VcAdapter (this)); instead of lv.setAdapter(new VcAdapter (this));.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!