Develop an android application with a context menu having menu items “Red”, “Yellow”,“Green”, “Black” and “Blue”, etc.
and
change the background color of the layout when the user selects the menu item accordingly.
menu_item.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="[Link]
<item android:id="@+id/red_menu_item" android:title="Red"/>
<item android:id="@+id/yellow_menu_item" android:title="Yellow"/>
<item android:id="@+id/green_menu_item" android:title="Green"/>
<item android:id="@+id/black_menu_item" android:title="Black"/>
<item android:id="@+id/blue_menu_item" android:title="Blue"/>
</menu>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:id="@+id/layout">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Long Press Here for Context Menu"
android:textSize="18sp"
android:layout_centerInParent="true"
android:padding="20dp"
android:background="#d6dd8b"
android:textColor="#000000"/>
</RelativeLayout>
[Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity {
private RelativeLayout layout;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
layout = findViewById([Link]);
textView = findViewById([Link]);
// Register context menu to the TextView
registerForContextMenu(textView);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, [Link]
menuInfo) {
[Link](menu, v, menuInfo);
[Link]("Choose a Color");
MenuInflater menuInflater = getMenuInflater();
[Link]([Link].menu_item,menu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
int itemId = [Link]();
if (itemId == [Link].red_menu_item) {
[Link]([Link]);
[Link]("Red Selected");
} else if (itemId == [Link].yellow_menu_item) {
[Link]([Link]);
[Link]("Yellow Selected");
} else if (itemId == [Link].green_menu_item) {
[Link]([Link]);
[Link]("Green Selected");
} else if (itemId == [Link].black_menu_item) {
[Link]([Link]);
[Link]("Black Selected");
} else if (itemId == [Link].blue_menu_item) {
[Link]([Link]);
[Link]("Blue Selected");
} else {
return [Link](item);
}
return true;
}
}