我从主要活动中调用片段:
<fragment
android:name="com.example.project.AdExample"
android:id="@+id/button_fragment"
android:layout_height="wrap_content"
android:layout_width="match_parent"
tools:layout="@layout/ad_example"/>
AdExample.java 源代码:
public class AdExample extends Fragment {
private ListView listView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// getting access to layout
View view = inflater.inflate(R.layout.ad_example, container, false);
listView = (ListView) view.findViewById(R.id.listView);
MovieAdapter adapter = new MovieAdapter(getActivity(), initData());
listView.setAdapter(adapter);
return view;
}
private List<MovieItem> initData () {
List<MovieItem> list = new ArrayList<MovieItem>();
list.add(new MovieItem("Item1", "Desc1", 2014));
list.add(new MovieItem("Item2", "Desc2", 2014));
list.add(new MovieItem("Item3", "Desc3", 2014));
return list;
}
}
但结果我得到一个空白的ListView。我在上面的代码中遗漏了什么吗?
感谢。
UPD:
这是 MovieAdapter.java 源代码:
public class MovieAdapter extends BaseAdapter {
private List<MovieItem> list;
private LayoutInflater layoutInflater;
public MovieAdapter(Context context, List<MovieItem> list) {
this.list = list;
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return 0;
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = layoutInflater.inflate(R.layout.movie_item, parent, false);
}
TextView name = (TextView) view.findViewById(R.id.nameText);
name.setText(getMovieItem(position).getName());
return view;
}
private MovieItem getMovieItem(int position ) {
return (MovieItem) getItem(position);
}
}
答案 0 :(得分:1)
您的获取计数返回0.
做:
@Override
public int getCount() {
return list.size();
}