实现上下文菜单到ListView?

问题描述:

我想为列表创建一个上下文菜单。实现上下文菜单到ListView?

<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

列表为空,因为您没有设置内容视图。 – Luksprog

+0

首先设置内容查看然后使用findViewByID –

+0

,但然后我得到一个错误,因为我在xml中使用android:id =“@ + id/list” 。当我试图使用android:id =“@ android:id/list”和 ListView list =(ListView)findViewById(android.R.id.list); ,我没有得到错误,但仍然没有上下文菜单(我没有实现onCreate) – user1624426

检查下面的代码

@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; 
} 

好运。