Example code of long press photo pop-up right-click menu function in Android
Scene Effect
Note:
realization
Change the layout to LinearLayout and set it as a vertical layout through Android: orientation = "vertical" >.
Then add an ImageView and set the ID property and the image source.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".LongClickActivity"> <ImageView android:id="@+id/image" android:src="@drawable/dog" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout>
Then come to the activity. First override the oncreatecontextmenu method in the activity. This method can add a menu and add menu items
//在activity中重写onCreateContextMenu菜单,为菜单添加选项值 @Override public void onCreateContextMenu(ContextMenu menu,View v,ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu,v,menuInfo); menu.add("收藏"); menu.add("举报"); }
Then register the long press event into the menu in the oncreate method and open the menu.
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_long_click); //将长按事件注册到菜单中,并打开菜单 ImageView imageView = (ImageView) findViewById(R.id.image); imageView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { //注册菜单 registerForContextMenu(v); //打开菜单 openContextMenu(v); return true; } }); }
Complete sample code
package com.badao.relativelayouttest; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.ContextMenu; import android.view.View; import android.widget.ImageView; public class LongClickActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_long_click); //将长按事件注册到菜单中,并打开菜单 ImageView imageView = (ImageView) findViewById(R.id.image); imageView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { //注册菜单 registerForContextMenu(v); //打开菜单 openContextMenu(v); return true; } }); } //在activity中重写onCreateContextMenu菜单,为菜单添加选项值 @Override public void onCreateContextMenu(ContextMenu menu,menuInfo); menu.add("收藏"); menu.add("举报"); } }
summary
The above is the example code of realizing the right-click menu function by long pressing photos in Android introduced by Xiaobian. I hope it will be helpful to you. If you have any questions, please leave me a message and Xiaobian will reply to you in time. Thank you very much for your support to our website! If you think this article is helpful to you, welcome to reprint, please indicate the source, thank you!