Full source of Android to create a floating context menu, which will appear when we long click on a particular view or item. For this we will create a menu xml file, override onCreateContextMenu to inflate this menu, use the registerForContextMenu method to set it on a TextView and finally handle clicks by overriding onContextItemSelected and check for the ID of the clicked item. Lastly we will learn, how to add a header title to our floating context menu by using the setHeaderTitle method
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
tools:context="tech.codingpoint.floatingcontextmenuexample.MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
example_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/option_1"
android:title="Option 1" />
<item
android:id="@+id/option_2"
android:title="Option 2" />
</menu>
MainActivity.java
package tech.codingpoint.floatingcontextmenuexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = findViewById(R.id.text_view);
registerForContextMenu(textView);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Choose your option");
getMenuInflater().inflate(R.menu.example_menu, menu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.option_1:
Toast.makeText(this, "Option 1 selected", Toast.LENGTH_SHORT).show();
return true;
case R.id.option_2:
Toast.makeText(this, "Option 2 selected", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onContextItemSelected(item);
}
}
}