ListView的使用(二)长按弹出上下文菜单

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list);
        
        mDbHelper = new DiaryDbAdapter(this);
        mDbHelper.open();
        renderListView();
        ListView mylistView = getListView();
        mylistView.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
            @Override
            public void onCreateContextMenu(ContextMenu menu, View v,
                    ContextMenuInfo menuInfo) {
                menu.setHeaderTitle("选择操作");
                menu.add(0, 0, 0, "更新该条");
                menu.add(0, 1, 0, "删除该条");
            }
        });    
    }
    

listview实现长按弹出上下文菜单。要注意

<ListView android:id="@+id/android:list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

中的id是@+id/android:list,这个并不在R文件中产生对应的id。故findViewById方法不可取。一个Activity中就只有一个ListView,所以setListAdapter(notes)方法并不需要指定对哪一个listview使用。

ListView mylistView = getListView();/*Get the activity's list view widget*/

原文地址:https://www.cnblogs.com/hixin/p/4063262.html