代碼如下:
package com.example.fragmentbestpractice;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class NewsTitleFragment extends Fragment implements OnItemClickListener {
private ListView titleListView;
private List newsList;
private NewsAdapter adapter;
private boolean isTwoPane;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
newsList = getNews();
adapter = new NewsAdapter(activity, R.layout.news_item, newsList);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater
.inflate(R.layout.news_title_frag, container, false);
titleListView = (ListView) view
.findViewById(R.id.title_list);
titleListView.setAdapter(adapter);
titleListView.setOnItemClickListener(this);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
if (getActivity().findViewById(R.id.news_content_layout) != null) {
isTwoPane = true;
} else {
isTwoPane = false;
}
}
@Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
News news = newsList.get(position);
if (isTwoPane) {
NewsContentFragment newsContentFragment = (NewsContentFragment) getFragmentManager()
.findFragmentById(R.id.news_content_fragment);
newsContentFragment.refresh(news.getTitle(), news.getContent());
} else {
NewsContentActivity.actionStart(getActivity(), news.getTitle(),
news.getContent());
}
}
public List<News> getNews() {
List<News> newslist = new ArrayList<News>();
News news1 = new News();
news1.setTitle("hahahaahhaahahahhahahaha");
news1.setContent("hohohohohohhohohohohohohohohohohoho" +
"hohohohohohohohohohohohohohohohohohohohohohohoh");
newslist.add(news1);
News news2 = new News();
news2.setTitle("qoqoqoqoqqoqoqoqoqoqoqoqoqoqo");
news2.setContent("bobobobobobobbobobobbo" +
"bobobobobobobobobobobbobobobobbobobobobob" +
"bobobooboobobobbobhahahahdhdhabobobobobobobobob");
newslist.add(news2);
return newsList;
}
}
日志中錯誤提示在這一句中: titleListView.setAdapter(adapter); 網上查了一天了,還是找不到原因,求大神們指教
小兄弟,建議你初始化的初始化數據的操作寫在onCreate()方法裡面。理解你為什麼寫在onAttach()中但容易發生錯誤,你最好吧LogCat打印出來的信息發出來看看,報的錯我認為應該不是adapter空指針錯誤,你看看打印出來含有Cause by的那一行是什麼錯誤,下面應該就是錯誤代碼所在的地方,個人認為是你的adapter裡面有問題,OnAttach()是Fragment生命周期的開始,在那裡初始化不存在adapter為Null的情況。