Android ListFragment:如何同时选择onListItemClick和OnContextItem?

Android ListFragment:如何同时选择onListItemClick和OnContextItem?,android,android-listfragment,contextmenu,Android,Android Listfragment,Contextmenu,我正在实现一个ListActivity和ListFragment,并希望允许用户使用短点击和长点击-短点击编辑/显示项目的详细信息,长点击打开一个上下文菜单,其中包含删除项目的选项。然而,我似乎无法触发onCreateContextMenu。onListItemClick工作正常,可以捕获所有的点击,无论是短点击还是长点击。ListFragment是使用稍微自定义的SimpleCursorAdaptor和LoaderManager填充的,而不是使用布局文件 两者都有可能吗 代码 Location

我正在实现一个ListActivity和ListFragment,并希望允许用户使用短点击和长点击-短点击编辑/显示项目的详细信息,长点击打开一个上下文菜单,其中包含删除项目的选项。然而,我似乎无法触发onCreateContextMenu。onListItemClick工作正常,可以捕获所有的点击,无论是短点击还是长点击。ListFragment是使用稍微自定义的SimpleCursorAdaptor和LoaderManager填充的,而不是使用布局文件

两者都有可能吗

代码

LocationsListFragment.java

package com.level3.connect.locations;

//import removed for brevity

public class LocationsListFragment extends SherlockListFragment implements LoaderManager.LoaderCallbacks<Cursor>{

private static final int DELETE_ID = Menu.FIRST + 1;    

private SimpleCursorAdapter adapter;
private OnLocationSelectedListener locationSelectedListener;

// the activity attaching to this fragment should implement this interface
public interface OnLocationSelectedListener {
    public void onLocationSelected(String locationId);
}    

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    // Fields from the database (projection)
    // Must include the _id column for the adapter to work
    String[] from = new String[] { LocationsTable.LOCATION_NAME, 
            LocationsTable.LOCATION_PHONE_NAME };
    // Fields on the UI to which we map
    int[] to = new int[] { R.id.titleText, R.id.phoneText };

    // connect to the database
    getLoaderManager().initLoader(0, null, this);
    adapter = new LocationCursorAdapter(getActivity(), 
            R.layout.location_row, null, from, to, 0);

    setListAdapter(adapter);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View root = super.onCreateView(inflater, container, savedInstanceState);    
    registerForContextMenu(root); //this is called fine
    return root;
}

// hook up listening for the user selecting a location in the list
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        locationSelectedListener = (OnLocationSelectedListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnLocationSelectedListener");
    }
}

// handle user tapping a location - show a detailed view - this works fine
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    String projection[] = { LocationsTable.KEY_ID };
    Cursor locationCursor = getActivity().getContentResolver().query(
            Uri.withAppendedPath(DatabaseContentProvider.CONTENT_URI,
                    String.valueOf(id)), projection, null, null, null);
    if (locationCursor.moveToFirst()) {
        String locationUrl = locationCursor.getString(0);
        locationSelectedListener.onLocationSelected(locationUrl);
    }
    locationCursor.close();
}

// Context menu - this is never called
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
        ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    menu.add(0, DELETE_ID, 0, R.string.menu_delete);
}

@Override - this is never called
public boolean onContextItemSelected(android.view.MenuItem item) {
    switch (item.getItemId()) {
    case DELETE_ID:
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
                .getMenuInfo();
        Uri uri = Uri.parse(DatabaseContentProvider.CONTENT_URI + "/"
                + info.id);
        getActivity().getContentResolver().delete(uri, null, null);
        return true;
    }
    return super.onContextItemSelected(item);
}

// Loader code
// Creates a new loader after the initLoader () call
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    String[] projection = { LocationsTable.KEY_ID, LocationsTable.LOCATION_NAME, LocationsTable.LOCATION_PHONE_NAME };
    CursorLoader cursorLoader = new CursorLoader(getActivity(),
            DatabaseContentProvider.CONTENT_URI, projection, null, null, null);
    return cursorLoader;
}

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    adapter.swapCursor(data);
}

@Override
public void onLoaderReset(Loader<Cursor> loader) {
    // data is not available anymore, delete reference
    adapter.swapCursor(null);
}

}
LocationsListFragment.java
包com.level3.connect.locations;
//为简洁起见,已删除导入
公共类LocationsListFragment扩展SherlockListFragment实现LoaderManager.LoaderCallbacks{
私有静态最终int DELETE_ID=Menu.FIRST+1;
专用SimpleCursorAdapter适配器;
私有OnLocationSelectedListener位置SelectedListener;
//附加到此片段的活动应实现此接口
公共接口OnLocationSelectedListener{
public void onLocationSelected(字符串位置ID);
}    
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//数据库中的字段(投影)
//必须包含_id列,适配器才能工作
String[]from=新字符串[]{LocationsTable.LOCATION\u NAME,
LocationsTable.LOCATION\u PHONE\u NAME};
//我们映射到的UI上的字段
int[]to=newint[]{R.id.titleText,R.id.phoneText};
//连接到数据库
getLoaderManager().initLoader(0,null,this);
适配器=新位置光标或适配器(getActivity(),
R.layout.location_行,null,from,to,0);
setListAdapter(适配器);
}
@凌驾
创建视图上的公共视图(布局、充气机、视图组容器、,
Bundle savedInstanceState){
视图根=super.onCreateView(充气机、容器、savedInstanceState);
registerForContextMenu(root);//这称为fine
返回根;
}
//连接监听用户在列表中选择的位置
@凌驾
公共事务主任(活动){
超级转速计(活动);
试一试{
locationSelectedListener=(OnLocationSelectedListener)活动;
}catch(ClassCastException e){
抛出新的ClassCastException(activity.toString()
+“必须实现OnLocationSelectedListener”);
}
}
//处理用户点击位置-显示详细视图-这很好
@凌驾
public void onListItemClick(列表视图l、视图v、整数位置、长id){
字符串投影[]={LocationsTable.KEY_ID};
游标位置游标=getActivity().getContentResolver().query(
withAppendedPath(DatabaseContentProvider.CONTENT\u Uri,
字符串.valueOf(id)),投影,null,null,null);
if(locationCursor.moveToFirst()){
String locationUrl=locationCursor.getString(0);
locationSelectedListener.onLocationSelected(locationUrl);
}
locationCursor.close();
}
//上下文菜单-从未调用过它
@凌驾
public void onCreateContextMenu(ContextMenu,视图v,
上下文菜单信息(menuInfo){
super.onCreateContextMenu(menu,v,menuInfo);
menu.add(0,DELETE\u ID,0,R.string.menu\u DELETE);
}
@覆盖-从未调用过它
公共布尔值onContextItemSelected(android.view.MenuItem项){
开关(item.getItemId()){
案例编号:
AdapterContextMenuInfo信息=(AdapterContextMenuInfo)项
.getMenuInfo();
Uri=Uri.parse(DatabaseContentProvider.CONTENT_Uri+“/”
+信息id);
getActivity().getContentResolver().delete(uri,null,null);
返回true;
}
返回super.onContextItemSelected(项目);
}
//加载器代码
//在initLoader()调用之后创建新的加载程序
@凌驾
公共加载器onCreateLoader(int-id,Bundle-args){
String[]projection={LocationsTable.KEY\u ID,LocationsTable.LOCATION\u NAME,LocationsTable.LOCATION\u PHONE\u NAME};
CursorLoader CursorLoader=新的CursorLoader(getActivity(),
DatabaseContentProvider.CONTENT_URI,投影,null,null,null);
返回游标装入器;
}
@凌驾
public void onLoadFinished(加载器、光标数据){
适配器。swapCursor(数据);
}
@凌驾
公共void onLoaderReset(加载器){
//数据不再可用,请删除引用
适配器.swapCursor(空);
}
}

更新:我仍然没有弄明白这一点,我想知道我是否必须放弃这个策略,以其他方式实施它,而不是以用户友好的方式。也许只需轻扫即可查看详细信息,轻按即可删除?

我已在本机电子邮件应用程序的Android源代码中找到了我的答案

ListFragment必须实现侦听器:

public class MessageListFragment extends SherlockListFragment
    implements LoaderManager.LoaderCallbacks<Cursor>, AdapterView.OnItemLongClickListener

    private static final int DELETE_ID = Menu.FIRST + 1;    

    private SimpleCursorAdapter adapter;

    // The LoaderManager needs initializing
    @Override
    public void onCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);

       // Fields from the database (projection)
       // Must include the _id column for the adapter to work
       String[] from = new String[] { BookmarksTable.BOOKMARK_NAME, 
            BookmarksTable.BOOKMARK_PHONE_NAME };
       // Fields on the UI to which we map
       int[] to = new int[] { R.id.titleText, R.id.phoneText };

       // connect to the database
       getLoaderManager().initLoader(0, null, this);
       adapter = new BookmarkCursorAdapter(getActivity(), 
            R.layout.bookmark_row, null, from, to, 0);

       setListAdapter(adapter);
    }

    // register to put up the context menu
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
       View root = super.onCreateView(inflater, container, savedInstanceState); 
       registerForContextMenu(root);
       return root;
    }

    // set the listeners for long click
    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        getListView().setOnItemLongClickListener(this);
    }
公共类MessageListFragment扩展了SherlockListFragment
实现LoaderManager.LoaderCallbacks、AdapterView.OnItemLongClickListener
私有静态最终int DELETE_ID=Menu.FIRST+1;
专用SimpleCursorAdapter适配器;
//LoaderManager需要初始化
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//数据库中的字段(投影)
//必须包含_id列,适配器才能工作
String[]from=新字符串[]{BookmarksTable.BOOKMARK\u NAME,
BookmarksTable.BOOKMARK\u PHONE\u NAME};
//我们映射到的UI上的字段
int[]to=newint[]{R.id.titleText,R.id.phoneText};
//连接到数据库
getLoaderManager().initLoader(0,null,this);
适配器=新书签游标适配器(getActivity(),
R.layout.bookmark_行,null,from,to,0);
setListAdapter(适配器);
}
//注册以显示上下文菜单
@凌驾
创建视图上的公共视图(布局、充气机、视图组容器、,
捆绑
 /**
  * Called when a message is clicked.
  */
 @Override
 public void onListItemClick(ListView parent, View view, int position, long id) {
        // do item click stuff; show detailed view in my case

 }


@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
    return false; // let the system show the context menu
  }

// Context menu
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
        ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    menu.add(0, DELETE_ID, 0, R.string.menu_delete);
}

    // respond to the context menu tap
@Override
public boolean onContextItemSelected(android.view.MenuItem item) {
    switch (item.getItemId()) {
    case DELETE_ID:
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
                .getMenuInfo();
        Uri uri = Uri.parse(DatabaseContentProvider.BOOKMARK_ID_URI + Long.toString(info.id));
        getActivity().getContentResolver().delete(uri, null, null);
        return true;
    }
    return super.onContextItemSelected(item);
}
// Loader code
// Creates a new loader after the initLoader () call
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    String[] projection = { BookmarksTable.KEY_ID, BookmarksTable.BOOKMARK_NAME, BookmarksTable.BOOKMARK_PHONE_NAME };
    CursorLoader cursorLoader = new CursorLoader(getActivity(),
            DatabaseContentProvider.BOOKMARKS_URI, projection, null, null, null);
    return cursorLoader;
}

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    adapter.swapCursor(data);
}

@Override
public void onLoaderReset(Loader<Cursor> loader) {
    // data is not available anymore, delete reference
    adapter.swapCursor(null);
}