本文主要是介绍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" ><TextView android: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定义" /><EditText android: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;}
}
这篇关于android:使用XML文件定义菜单项的选项菜单的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!