实现ListView的上下文菜单?

时间:2012-08-25 11:46:05

标签: java android android-menu

我正在尝试为列表创建上下文菜单。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" 
android:orientation="vertical" >

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

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // setContentView(R.layout.activity_main);
    content = new ArrayList<HashMap<String,String>>();

    ListView list = (ListView)findViewById(R.id.list);
    registerForContextMenu(list);
}    

当它到达registerForContextMenu(list);时,我收到运行时错误。

另一件事,当我在XML中使用android:id="@androidid/list"时,我该如何引用该列表? 我尝试过ListView list = (ListView)findViewById(android.R.id.list);,但仍然出错 注册上下文菜单。

1 个答案:

答案 0 :(得分:0)

检查以下代码

 @Override  
public void onCreate(Bundle savedInstanceState) {  
    super.onCreate(savedInstanceState);  
    setContentView(R.layout.main);  

    lview3 = (ListView) findViewById(R.id.listView3);  

    adapter = new ListviewAdapter(this, month, desc, icons);  
         // set here your listview adapter value
    lview3.setAdapter(adapter);  

    //for context menu
    registerForContextMenu(lview3);

}

//start from here context menu//

@Override
public void onCreateContextMenu(ContextMenu menu, View v,
        ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    menu.setHeaderTitle("select");
    menu.add(0, v.getId(), 0, "Action 1");
    menu.add(0, v.getId(), 0, "Action 2");
    menu.add(0, v.getId(), 0, "Action 3");
}


@Override
public boolean onContextItemSelected(MenuItem item) {
    if (item.getTitle() == "Action 1") {
        //
    } else if (item.getTitle() == "Action 2") {
        //
    } else {
        return false;
    }
    return true;
}

祝你好运。