http://blog.csdn.net/wannerwang/article/details/50532271
Use of ContextMenu
ContextView , related to the context, the idea is similar to the shortcut menu that pops up when you right-click and click to build in Windows . The operation is to hold down a component for a long time.
The effect is as follows:
Long press as follows:
The creation steps are as follows:
1 Override Activity 's onCreateContextMenu () method and call Menu 's add () method to add menu items
2 : Override Activity 's onContextItemSelected (MenuItem item) to respond to the event.
3 : Call the registForContextMenu () method to register the context menu for the view.
Note: Only one ContenxtMenu can be used in one interface .
ContextMenu also has two registration methods.
The implementation process of Xml registration is as follows:
In the res / menu to create a folder context_menu.xml file
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity">
<item
android:id="@+id/red"
android:orderInCategory="100"
android:title="红色" />
<item
android:id="@+id/green"
android:orderInCategory="200"
android:title="绿色" />
<item
android:id="@+id/blue"
android:orderInCategory="300"</menu>" />blue
android:title="
在MianActivity文件中加载布局文件。
package com.xiyou.com.meanususe;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
//上下文菜单
public class ContextMenuus extends AppCompatActivity {
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.context_menu);
// 注册上下文菜单到TextView组件上
registerForContextMenu(tv);
}
// 创建上下文菜单的事件方法
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
getMenuInflater().inflate(R.menu.context_menu, menu);
super.onCreateContextMenu(menu, v, menuInfo);
}
// 上下文菜单的单击事件
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.red:
tv.setBackgroundColor(Color.RED);
break;
case R.id.green:
tv.setBackgroundColor(Color.GREEN);
break;
case R.id.blue:
tv.setBackgroundColor(Color.BLUE);
break;
}
return super.onContextItemSelected(item);
}
}