可以在每个View控件上注册一个长按点击事件,触发弹出一个悬浮的菜单,也成为上下文菜单
菜单视图部分 xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:title="登录"
android:id="@ id/login"
/>
<item android:title="注册"
android:id="@ id/register"
/>
</menu>
菜单逻辑代码 java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerForContextMenu(findViewById(R.id.btn));
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
getMenuInflater().inflate(R.menu.first, menu);
}
@Override
public boolean onContextItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.login:
Toast.makeText(this, "你刚刚点了登录", Toast.LENGTH_LONG).show();
break;
case R.id.register:
Toast.makeText(this, "你刚刚点了注册", Toast.LENGTH_LONG).show();
break;
}
return true;
}
}