Can I extend the context menu from a custom class (not an Activity class)?… here is a solution to the problem.
Can I extend the context menu from a custom class (not an Activity class)?
I’m writing an application where I want to populate a gridview with objects I made myself. The code for my custom object is as follows. I want my object to be able to extend the context menu.
My problem is that I can’t seem to use the getMenuInflater() method outside of the Activity class. To bypass this limitation, I pass my main activity to the object. While this does make me call the getMenuInflater() method, I still don’t see the menu when I run the code.
Thanks for any help!
I know I can extend the menu directly from the Activity class. However, if possible, I’d like to keep all of these features in a custom object.
import java.io.File;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
public class AnimalKind extends ImageView implements OnClickListener, OnLongClickListener{
private int m_imageId, m_soundId;
private Context m_ctx;
private Activity m_activity;
public AnimalKind(Context ctx, int imageId, int soundId, Activity act) {
super(ctx);
m_imageId = imageId;
m_activity = act;
m_ctx = ctx;
super.setImageResource(imageId);
super.setAdjustViewBounds(true);
super.setScaleType(ImageView.ScaleType.FIT_XY);
super.setPadding(1, 1, 1, 1);
super.setBackgroundColor(Color.BLACK);
super.setOnClickListener(this);
super.setOnLongClickListener(this);
m_activity.registerForContextMenu(this);
}
@Override
protected void onCreateContextMenu(ContextMenu menu) {
super.onCreateContextMenu(menu);
MenuInflater inflater = m_activity.getMenuInflater();
inflater.inflate(R.menu.animal_kind_menu, menu);
}
@Override
public void onClick(View v) {
Do stuff
}
@Override
public boolean onLongClick(View v) {
Do stuff
}
}
Solution
This worked for me: instead of trying to extend the menu from XML, I created the menu item directly from java:
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
menu.add(1, 1, 1, "Share Animal Sound");
menu.add(1, 2, 2, "Change Picture");
menu.add(1, 3, 3, "Change Sound");
menu.getItem(0).setOnMenuItemClickListener(this);
menu.getItem(1).setOnMenuItemClickListener(this);
menu.getItem(2).setOnMenuItemClickListener(this);
}