我是一个遵循一本书的android初学者。现在我遇到了一个问题。测试应用程序是一个新闻应用程序,代码如下:
public class NewsTitleFragment extends Fragment implements OnItemClickListener {
private ListView newsTitleListView;
private List<News> newsList;
private NewsAdapter adapter;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
newsList = getNews();
adapter = new NewsAdapter((Activity)activity, R.layout.news_item, newsList);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater
.inflate(R.layout.news_title_frag, container, false);
newsTitleListView = (ListView) view
.findViewById(R.id.news_title_list_view);
newsTitleListView.setAdapter(adapter);
newsTitleListView.setOnItemClickListener(this);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (getActivity().findViewById(R.id.news_content_layout) != null) {
isTwoPane = true;
} else {
isTwoPane = false;
}
}
@Override
public void onItemClick(AdapterView<?> parent, 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());
}
}
private List<News> getNews() {
List<News> newsList = new ArrayList<News>();
News news1 = new News();
news1.setTitle("It's news 1");
news1.setContent("It's news 1 content");
newsList.add(news1);
News news2 = new News();
news2.setTitle("It's news 2");
news2.setContent("It's news 2 content");
newsList.add(news2);
return newsList;
}
}
但在新的 android API 中,代码
public void onAttach(Activity activity)
必须改为
public void onAttach(Context context)
我更改了它,但应用程序在更改后显示任何内容!我想知道为什么我错了以及如何改变它。非常感谢。PSNewsAdapter 类扩展了 ArrayAdapter。News 类只有两个字符串 NewsAdapter 方法是:
public class NewsAdapter extends ArrayAdapter<News> {
private int resourceId;
public NewsAdapter(Context context, int textViewResourceId, List<News> objects) {
super(context, textViewResourceId, objects);
resourceId = textViewResourceId;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
News news = getItem(position);
View view;
if (convertView == null) {
view = LayoutInflater.from(getContext()).inflate(resourceId, null);
} else {
view = convertView;
}
TextView newsTitleText = (TextView) view.findViewById(R.id.news_title);
newsTitleText.setText(news.getTitle());
return view;
}
}