1

我正在尝试为列表制作上下文菜单。

<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);,我得到一个运行时错误。

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

4

1 回答 1

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

祝你好运。

于 2012-08-25T12:40:03.353 回答