如何在单击上下文菜单时启动意图活动?

时间:2013-12-18 13:55:09

标签: android android-intent android-contextmenu

当我在列表视图上长按一个项目时,我已经成功创建了浮动上下文菜单。但是,当我单击上下文菜单上的菜单时,没有任何事情发生。我想让它开始一项新的活动。有什么不对?

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_activity_view);

    dataSource = new DBDataSource(this);

    dataSource.open();

    values = dataSource.getAllMahasiswa();

    ArrayAdapter<Mahasiswa> adapter = new ArrayAdapter<Mahasiswa>
    (this, android.R.layout.simple_list_item_1, values);

    setListAdapter(adapter);

    listView=(ListView) findViewById(android.R.id.list);
    registerForContextMenu(listView);



}
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);

        menu.add(0, 1000, 0, "Edit");  
        menu.add(0, 1001, 0, "Hapus"); 

} 

public boolean onContextMenuItemSelected(MenuItem item){
     switch (item.getItemId()) {
       case 1000:             
           Intent i = new Intent(ActivityView.this, Tes.class);

           startActivity(i);
       break; 
       case 1001:
          //not yet
       break;
       }
       return super.onContextItemSelected(item);           

 }

1 个答案:

答案 0 :(得分:0)

使用此

@Override
public boolean onContextItemSelected(MenuItem item)
{
        switch (item.getItemId())
        {
        case R.id.pick_camera:

            break;
        }
    return super.onContextItemSelected(item);
}

@Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
    {

         getMenuInflater().inflate(R.menu.image_options, menu);
        super.onCreateContextMenu(menu, v, menuInfo);
    }

在资源的菜单文件夹中创建image_options.xml。

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/pick_camera"
        android:title="Use Camera">
    </item>

</menu>