onListItemClick不起作用......为什么?

时间:2015-02-22 22:48:25

标签: android android-arrayadapter

我试着教我制作一个带有片段的列表。我现在已经创建了一个自定义数组适配器,以使我的行在列表中适应我的应用程序。但是,按下该项目时没有任何反应。但是,按预期工作复选框(?)

我做错了什么?

提前致谢

List_Fragment

public class List_Fragment extends ListFragment{

    ArrayList<Detail> items= new ArrayList<Detail>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View root = inflater.inflate(R.layout.list_layout, container, false);

        CustomAdapter adapter = new CustomAdapter(getActivity(), items);
        setListAdapter(adapter);

        return root;
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);

        Detail detail = items.get(position);
        Toast.makeText(getActivity(), detail.getTitle(), Toast.LENGTH_LONG).show();
    }

    public void setItems(ArrayList<Detail> items) {
        this.items = items;
    }
}

CustomAdapter

@Override
public View getView(int position, View convertView, ViewGroup parent){


LayoutInflater theInflater = LayoutInflater.from(getContext());
View view = theInflater.inflate(R.layout.list_row, parent, false);

final Detail title = getItem(position);

TextView titleView = (TextView)view.findViewById(R.id.itemTitle);

titleView.setText(title.getTitle());

CheckBox chkbox = (CheckBox)view.findViewById(R.id.itemDone);

chkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView,
            boolean isChecked) {
        title.setDone(true);
    }
});         

return view;

}

1 个答案:

答案 0 :(得分:1)

您的OnListItemClicked()OnCheckChangedListener彼此之间存在冲突。

我认为您需要在CheckBox上设置属性android:focusable="false"。您可能还需要在ListFragment上调用getListView().setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS)。请参阅其他SO问题“onitemselected not working”,因为这有不同之处。

此外,我注意到您的setItems()方法只设置了您的成员变量,并且没有更新适配器。

public void setItems(ArrayList<Detail> items) {
    // this.items = items;
    CustomAdapter adapter = (CustomAdapter) getListView().getAdapter();
    adapter.clear();
    adapter.addAll(items);
    adapter.notifyDataSetChanged();
}

这将使您的列表正确更新。

(取出原始代码,因为我忘了ArrayAdapterclear()add()insert()等方法。所以你不需要扩展{{ 1}}。)