我正在制作一个将放在另一个视图下的列表。 根据另一篇文章,我应该在listview的标题中包含另一个视图。 我正在使用ListFragment并将附加到几个活动。所以我正在创建一个方法来设置ListFragment的标题。
问题是getListView()方法返回null,尽管我在显示列表后调用了addHeader。
为什么getListView()始终为null?
这是我的代码:
public class NewsListFragment extends ListFragment {
private final int topNewsCount = 5;
private DBNewsDataSource dataSource;
private Activity myActivity;
private Context myContext;
private boolean isHome;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
isHome = true;
myActivity = getActivity();
Bundle extras = myActivity.getIntent().getExtras();
if (extras != null) {
isHome = extras.getBoolean("isHome");
}
dataSource = new DBNewsDataSource(getActivity());
dataSource.open();
List<DBNews> news = dataSource.getAllNews();
List<String> titleList = new ArrayList<String>();
dataSource.close();
for(int i = 0; i< (isHome?topNewsCount:news.size()); i++)
{
titleList.add(news.get(i).getTitle());
}
NewsListArrayAdapter adapter = new NewsListArrayAdapter(getActivity(),news,titleList,isHome);
setListAdapter(adapter);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Do something with the data
}
public void addHeader(View v)
{
ListView lv = getListView();
lv.addHeaderView(v);
}
以下是调用Fragment的活动
public class HomeActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.template_activity_home);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
NewsListFragment frgNews = new NewsListFragment();
MainSlideShowFragment frgSS = new MainSlideShowFragment();
View vw = frgSS.getView();
frgNews.addHeader(vw);
fragmentTransaction.add(R.id.layout_news_list , (Fragment) frgNews);
fragmentTransaction.commit();
//frgNews.addHeader(vw);
}
答案 0 :(得分:0)
您正在使用片段但未被称为
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.example_fragment, container, false);
}
这是布局膨胀的地方。因此它是空的,因为它还没有膨胀。
答案 1 :(得分:0)
覆盖onCreate视图并让它返回一个包含ID为android:id="@android:id/list"
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.cart_list,
null);
return view;
}