本文实例为大家分享了ContextMenu长按事件的实现具体代码,供大家参考,具体内容如下
public class MyContextMenu extends AppCompatActivity {
final static int CONTEXT_MENU_1 = Menu.FIRST;//可以理解为ID设置的最小数值
final static int CONTEXT_MENU_2 = Menu.FIRST + 1;
final static int CONTEXT_MENU_3 = Menu.FIRST + 2;
TextView textView = null;//设置成员变量
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_context_menu);
textView = (TextView)findViewById(R.id.label);//获取text
registerForContextMenu(textView);//注册长摁菜单事件
}
@Override
public void onCreateContextMenu(ContextMenu menu,
View v, ContextMenu.ContextMenuInfo menuInfo){
menu.setHeaderTitle("快捷菜单");//设置
//设置对应id及title
menu.add(0, CONTEXT_MENU_1, 0,"菜单子项1");
menu.add(0, CONTEXT_MENU_2, 1,"菜单子项2");
menu.add(0, CONTEXT_MENU_3, 2,"菜单子项3");
}
@Override
public boolean onContextItemSelected(MenuItem item){
switch(item.getItemId()){
case CONTEXT_MENU_1:
Toast.makeText(MyContextMenu.this,"选中菜单子项1",Toast.LENGTH_SHORT).show();
return true;
case CONTEXT_MENU_2:
Toast.makeText(MyContextMenu.this,"选中菜单子项2",Toast.LENGTH_SHORT).show();
return true;
case CONTEXT_MENU_3:
Toast.makeText(MyContextMenu.this,"选中菜单子项3",Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
public void skip(View v){
Intent intent = new Intent();
intent.setClass(MyContextMenu.this,TabDemo.class);//从前者跳往后者
startActivity(intent);//启动
}
}
xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MyContextMenu"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView android:id="@+id/label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>
效果图:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。