上下文菜单
1、重写Activity的onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)方法。
2、调用Activity的registerForContextMenu(textView)方法为View组件注册上下文菜单
2、重写Activity的onContextItemSelected(MenuItem item)响应菜单项的选择操作,调用item.getItemId()获得被点击菜单项的ID,做出不同的响应
package com.example.myapplication; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { //定义按钮的全局变量 private Button button; private TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 绑定按钮的资源(利用id找到xml文件中的按钮) button = findViewById(R.id.button); textView = findViewById(R.id.textView); //为组件注册上下文菜单 registerForContextMenu(textView); } //重写Activity的onCreateContextMenu() public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo){ switch (v.getId()){ case R.id.textView: menu.setHeaderTitle("分享到,,,"); menu.add(0,200,0,"qq空间"); menu.add(0,201,0,"朋友圈"); SubMenu submenu = menu.addSubMenu(0,200,0,"微博"); submenu.add(0,202,0,"新浪"); submenu.add(0,203,0,"新浪"); submenu.add(0,204,0,"新浪"); default: break; } super.onCreateContextMenu(menu,v,menuInfo); } //重写Activity的onContextItemSelected() public boolean onContextItemSelected(MenuItem item){ switch (item.getItemId()){ case 200: Toast.makeText(MainActivity.this,"你选了一",Toast.LENGTH_LONG).show(); break; case 201: Toast.makeText(MainActivity.this,"你选了二",Toast.LENGTH_LONG).show(); break; case 203: Toast.makeText(MainActivity.this,"你选了三",Toast.LENGTH_LONG).show(); break; case 204: Toast.makeText(MainActivity.this,"你选了四",Toast.LENGTH_LONG).show(); break; default: return super.onOptionsItemSelected(item); } return true; } }
效果图如下:(长按哦!)