我有一个片段 Tab1Fragment,它扩展了 Fragment 类(所以我不能扩展 ListActivity,这是调用 setListAdapter 方法所必需的)。在这个片段中,我想显示一个填充了自定义对象的列表视图。
有没有办法,我可以在不将扩展类更改为 ListFragment 的情况下设置适配器?问题在于 setListAdapter 方法(标有 # HERE)。
这是片段代码:
public class Tab1Fragment extends Fragment {
private ArrayList<MobileNETDistinctChatInfo> m_parts = new ArrayList<MobileNETDistinctChatInfo>();
private Runnable viewParts;
private MobileNETDistinctChatInfoAdapter m_adapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
MobileNETDBHandler db = new MobileNETDBHandler(getActivity());
// instantiate Adapter class
m_adapter = new MobileNETDistinctChatInfoAdapter(getActivity(), R.layout.chatlist_list_item, m_parts);
setListAdapter(m_adapter); # HERE
// Thread, which fetches data in the background
viewParts = new Runnable(){
public void run(){
handler.sendEmptyMessage(0);
}
};
Thread thread = new Thread(null, viewParts, "MagentoBackground");
thread.start();
return (LinearLayout) inflater.inflate(R.layout.tab1, container, false);
}
private Handler handler = new Handler()
{
public void handleMessage(Message msg)
{
m_parts.add(new MobileNETDistinctChatInfo("someone@gmail.com","Message1", "2013-01-01 11:11:11"));
m_parts.add(new MobileNETDistinctChatInfo("someonelse@gmail.com","Message2", "2013-01-01 11:11:11"));
m_parts.add(new MobileNETDistinctChatInfo("someonelselse@gmail.com","Message3", "2013-01-01 11:11:11"));
m_adapter = new MobileNETDistinctChatInfoAdapter(getActivity(), R.layout.chatlist_list_item, m_parts);
// display the list.
setListAdapter(m_adapter); # HERE
}
};
}
我不能使用 ListFragment,因为另一个类中的方法返回选项卡(它们被命名为 Tab1Fragment、Ta2Fragment、Tab3Fragment 并扩展了 Fragment 类),它属于 Fragment 类型,所以我不应该扩展 ListFragment。
方法:
@Override
public Fragment getItem(int position) {
Fragment fragment = new Fragment();
switch (position) {
case 0:
return fragment = new Tab1Fragment();
case 1:
return fragment = new Tab2Fragment();
case 2:
return fragment = new Tab3Fragment();
default:
break;
}
return fragment;
}