例如,当我在虚拟键盘上的“完成”软键上选择时,它将触发上下文菜单以显示带有“选项”标题的选项,例如“选项1”,“选项2”,“选项3”。
以下是我的xml文件的简化版本。
<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
android:keyWidth="10%p"
android:horizontalGap="0px"
android:verticalGap="0px"
android:keyHeight="@dimen/key_height"
>
<Row>
<Key android:codes="1" android:keyLabel="Encrypt" android:keyEdgeFlags="left"/>
<Key android:codes="2" android:keyLabel="Translate"/>
<Key android:codes="3" android:keyLabel="Done" android:keyEdgeFlags="right"/>
</Row>
</Keyboard>
最佳答案
要显示上下文菜单,请参见以下代码:
在Activity的onCreate方法中:
key.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//Creating the instance of PopupMenu
PopupMenu popup = new PopupMenu(MainActivity.this, button1);
//Inflating the Popup using xml file
popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());
//registering popup with OnMenuItemClickListener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(MainActivity.this,"You Clicked : " + item.getTitle(),Toast.LENGTH_SHORT).show();
return true;
}
});
popup.show();//showing popup menu
}
});//closing the setOnClickListener method
档案:poupup_menu.xml
<menu xmlns:androclass="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/one"
android:title="One"/>
<item
android:id="@+id/two"
android:title="Two"/>
<item
android:id="@+id/three"
android:title="Three"/>
</menu>