CustomListViewAdapter不能在片段中应用

时间:2014-02-21 16:24:33

标签: android android-listview android-fragments onitemclicklistener

知道为什么这会在开放时崩溃吗?我现在没有错。我再次阅读了本教程,无法理解为什么我的实现崩溃了。

即使取出OnItemClickListener()它仍然崩溃,我因错误而迷失。

public class findFragment extends Fragment implements AdapterView.OnItemClickListener{

    ListView list;
    List<RowItem> rowItems;

    public static final String[] titles = new String[] { "Strawberry",
            "Banana", "Orange", "Mixed" };

    public static final String[] descriptions = new String[] {
            "It is an aggregate accessory fruit",
            "It is the largest herbaceous flowering plant", "Citrus Fruit",
            "Mixed Fruits" };

    public static final Integer[] images = { R.drawable.test,
            R.drawable.test, R.drawable.test, R.drawable.test };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.find, container, false);

        rowItems = new ArrayList<RowItem>();
        for (int i = 0; i < titles.length; i++) {
            RowItem item = new RowItem(images[i], titles[i], descriptions[i]);
            rowItems.add(item);
        }

        list = (ListView) view.findViewById(R.id.list);

        CustomListViewAdapter adapter = new CustomListViewAdapter(getActivity(),
                R.layout.imglist, rowItems);
        list.setAdapter(adapter);
          list.setOnItemClickListener(this);

    return view;
}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
                        long id) {
    list.setItemChecked(position, true);
}

1 个答案:

答案 0 :(得分:1)

使用

  CustomListViewAdapter adapter = new CustomListViewAdapter(getActivity(),
            R.layout.imglist, rowItems);

getActivity()返回与此片段关联的活动。您需要的活动背景不是this

编辑:

   public class findFragment extends Fragment implements OnItemClickListener{

您需要覆盖onItemClick

   list.setOnItemClickListener(this);