0

我有活动。在活动中,我有片段(“MyFragment”)。在片段中,我有 listView。

然后在我接下来的代码中:

view.findViewById(R.id.my_fragment).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(final View v) {
        //SomeAction
    }
});

但是这个 onClick 不起作用。我认为是因为 ListView 覆盖了整个片段。

然后我接下来设置为列表视图:

android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"

但它不起作用。如何制作片段以捕获所有点击事件?

4

1 回答 1

0

如果您的片段中只有一个 ListView,最好使用ListFragment。OnitemClickListener 更好地集成。您只需要覆盖 OnListItem 侦听器

这里有很好的教程:http: //developer.android.com/guide/components/fragments.html

这是一个例子:

public class ListMenu extends android.support.v4.app.ListFragment {

private String[] strList = { "test1", "test2", "test3", "test4" };
OnMenuSelectedListener mCallback;

public interface OnMenuSelectedListener  {
    public void onMenuSelected(int position);
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    this.setListAdapter(new ArrayAdapter<String>(getActivity(),
            android.R.layout.simple_list_item_activated_1, strList));

}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    // This makes sure that the container activity has implemented
    // the callback interface. If not, it throws an exception.
    try {
        mCallback = (OnMenuSelectedListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnHeadlineSelectedListener");
    }
}

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


    mCallback.onMenuSelected(position);
    getListView().setItemChecked(position, true);
}

}
于 2013-02-13T16:10:56.883 回答