android ContextMenu 上下文菜单示例

ch2_contextmenu.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
    <TextView android:id="@+id/tv"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="这是一个上下文菜单ContextMenu的示例"/>
    
    <EditText android:id="@+id/myEd"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

ContextMenuActivity.java :

package com.example.ch7;



import com.example.baseexample.R;

import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.EditText;
import android.widget.TextView;

public class ContextMenuActivity extends Activity {

	private String tempStr;
	private TextView tv;
	private EditText myEd;
	
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch7_contextmenu);
		this.registerForContextMenu(findViewById(R.id.tv));
		this.registerForContextMenu(findViewById(R.id.myEd));
	}
	
	public void onCreateContextMenu(ContextMenu menu,View v,ContextMenuInfo menuInfo){
		menu.setHeaderIcon(R.drawable.ic_launcher);
		if(v==findViewById(R.id.tv)){
			menu.add(0,1,0,"复制");
			menu.add(0,2,0,"剪切");
			menu.add(0,3,0,"删除");
		}
		if(v==findViewById(R.id.myEd)){
			menu.add(0,4,0,"粘贴");
			menu.add(0,5,0,"删除");
		}
	}
	
	public boolean onContextItemSelected(MenuItem item){
		tv = (TextView)findViewById(R.id.tv);
		myEd = (EditText)findViewById(R.id.myEd);
		switch(item.getItemId()){
		case 1:
			tempStr = tv.getText().toString();
			break;
		case 2:
			tempStr = tv.getText().toString();
			tv.setText("");
			break;
		case 3:
			tv.setText("");
			break;
		case 4:
			myEd.setText(tempStr);
			break;
		case 5:
			myEd.setText("");
			break;
		}
		return true;
	}
	
	
}


转载于:https://my.oschina.net/u/2552902/blog/543895

猜你喜欢

转载自blog.csdn.net/weixin_34308389/article/details/92326857