首页 > 代码库 > android上下文菜单
android上下文菜单
XML:
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView android:id="@+id/txt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="上下文菜单"
android:textSize="25sp"/>
</RelativeLayout>
context_menu.xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/action_Edit"
android:orderInCategory="100"
android:showAsAction="never"
android:title="编辑"/>
<item
android:id="@+id/action_file"
android:orderInCategory="99"
android:title="打开"/>
<item
android:id="@+id/action_file"
android:orderInCategory="99"
android:title="复制"/>
<item android:title="Window">
<menu>
<item
android:id="@+id/newWin"
android:title="New Window"/>
<item
android:id="@+id/newEdit"
android:title="New Editor"/>
</menu>
</item>
</menu>
Activtiy:
public class MenuActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
TextView t=(TextView)findViewById(R.id.txt);
registerForContextMenu(t);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
//menu.add(Menu.NONE, Menu.FIRST, 1, "File");
menu.add(Menu.NONE, Menu.FIRST+1, 2, "Edit");
menu.add(Menu.NONE, Menu.FIRST+2, 3, "Refactor");
menu.add(Menu.NONE, Menu.FIRST+3, 4, "Source");
menu.add(Menu.NONE, Menu.FIRST+4, 5, "Navigate");
SubMenu file=menu.addSubMenu("File");
file.add(1, Menu.FIRST+20, 1, "新建");
file.add(1, Menu.FIRST+21, 2, "打开");
file.add(1, Menu.FIRST+22, 3, "保存");
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case Menu.FIRST+1:
Toast.makeText(this, "你点击了编辑",Toast.LENGTH_LONG).show();
break;
default:
break;
}
return false;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater=new MenuInflater(this);
inflater.inflate(R.menu.context_menu, menu);
menu.setHeaderTitle("分差差");
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.action_Edit:
Toast.makeText(this, "你点击了上下文菜单编辑",Toast.LENGTH_LONG).show();
break;
default:
break;
}
return super.onContextItemSelected(item);
}
}
android上下文菜单