我有一个弹出菜单,我正在为菜单中的项目实施操作;但是,当按下菜单“通知”中的第二项时,没有任何反应。第一项工作“更改图标”但不是第二项。我怀疑函数中的evenlistener有问题。如果有人能指出我这样做的正确方法。我检查android dev文档,他们实现了一点不同。 主要活动
package org.pctechtips.menulistview;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList hosts;
String ipAdd = "192.168.10.";
ListView list;
ArrayAdapter<String> adapter;
PopupMenu popup;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
hosts = new ArrayList<String>();
for(int i = 0; i < 255; i++) {
hosts.add(ipAdd+i);
}
list = (ListView) findViewById(R.id.list);
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.ip_address, hosts);
list.setAdapter(adapter);
//registering the menu with the listview
// registerForContextMenu(list);
}
/* code for popup menu in listview */
public void showPopupMenu(View v) {
popup = new PopupMenu(this, v);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.list_menu, popup.getMenu());
/* handling event listeners*/
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch(menuItem.getItemId()) {
case R.id.change_icon:
Toast.makeText(MainActivity.this, menuItem.getTitle(), Toast.LENGTH_SHORT).show();
return true;
case R.id.notifications:
Toast.makeText(MainActivity.this, menuItem.getTitle(), Toast.LENGTH_SHORT).show();
return true;
default:
return MainActivity.super.onOptionsItemSelected(menuItem);
}
}
});
popup.show();
}
}
弹出菜单xml文件
<!-- listview menu for host scan options eg:
change hostname, icon, notification etc -->
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<!-- Settings, should always be in the overflow -->
<item android:id="@+id/change_icon"
android:title="change icon"
app:showAsAction="always"/>
<itme android:id="@+id/notifications"
android:title="notifications"
app:showAsAction="always"/>
<item android:id="@+id/set_hostname"
android:title="set notification"
app:showAsAction="always"/>
</menu>
答案 0 :(得分:1)
您的菜单文件中有item
拼写错误的通知。
<itme android:id="@+id/notifications"
android:title="notifications"
app:showAsAction="always"/>
这可能是问题吗?
刚刚测试过,这似乎是个问题。纠正拼写,菜单应该可以正常工作。