AI智能
改变未来

android:使用XML文件定义菜单项的选项菜单


##长按文本显示菜单

##长按编辑框显示菜单

activity_main.xml

<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"android:layout_width=\"fill_parent\"android:layout_height=\"fill_parent\"android:orientation=\"vertical\" ><TextViewandroid:id =\"@+id/tv\"android:layout_width=\"match_parent\"android:layout_height=\"wrap_content\"android:textColor =\"#000000\"android:fontFamily =\"Arial\"android:textSize=\"20sp\"android:text=\"例1菜单项改为XML定义\" /><EditTextandroid:id =\"@+id/myEd\"android:layout_width=\"match_parent\"android:layout_height=\"wrap_content\" /></LinearLayout>

myed_menu.xml

<?xml version=\"1.0\" encoding=\"utf-8\"?><menu xmlns:android=\"http://schemas.android.com/apk/res/android\" ><item android:id=\"@+id/edPaste\"android:title=\"粘贴\"android:orderInCategory =\"4\" /><item android:id=\"@+id/edDelete\"android:title=\"删除\"android:orderInCategory=\"5\"/></menu>

tv_menu.xml

<?xml version=\"1.0\" encoding=\"utf-8\"?><menu xmlns:android=\"http://schemas.android.com/apk/res/android\" ><item android:id=\"@+id/copy\"android:title=\"复制\"android:orderInCategory =\"1\" /><item android:id=\"@+id/cut\"android:title=\"剪切\"android:orderInCategory=\"2\"/><item android:id=\"@+id/delete\"android:title=\"删除\"android:orderInCategory=\"3\" /></menu>

MainActivity.java

package com.example.ch5_2_1;import android.app.Activity;import android.os.Bundle;import android.view.ContextMenu;import android.view.MenuItem;import android.view.View;import android.widget.EditText;import android.widget.TextView;import android.view.ContextMenu.ContextMenuInfo;import android.view.MenuInflater;public class MainActivity extends Activity {private String tempStr; // 保存临时字符串@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//为对象注册ContextMenu事件registerForContextMenu(findViewById(R.id.tv));registerForContextMenu(findViewById(R.id.myEd));}@Overridepublic void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {menu.setHeaderIcon(R.drawable.ic_launcher);if (v == findViewById(R.id.tv)) {if (menu.size() == 0) {MenuInflater inflater = getMenuInflater();inflater.inflate(R.menu.tv_menu, menu);}}if (v == findViewById(R.id.myEd)) {if (menu.size() == 0) {MenuInflater inflater = getMenuInflater();inflater.inflate(R.menu.myed_menu, menu);}}}@Overridepublic boolean onContextItemSelected(MenuItem item) {TextView tv = (TextView) findViewById(R.id.tv);EditText myEd = (EditText) findViewById(R.id.myEd);switch (item.getItemId()) {case R.id.copy:tempStr = tv.getText().toString();break;case R.id.cut:tempStr = tv.getText().toString();tv.setText(\"\");break;case R.id.delete:tv.setText(\"\");break;case R.id.edPaste:myEd.setText(tempStr);break;case R.id.edDelete:myEd.setText(\"\");break;}return true;}}
赞(0) 打赏
未经允许不得转载:爱站程序员基地 » android:使用XML文件定义菜单项的选项菜单