BaseAdapter y ContextMenu
Hola comunidad de stackoverflow,
Básicamente, tengo la galería que exhibe algunas imágenes usando un gridView + imageView
- OnLongItemClick en RecyclerView
- Android para detectar cuando se mantiene pulsado un botón
- ¿Cómo evitar que OnItemClickListener trabaje cuando haga clic largo?
- Deshabilitar clic largo en la vista web de android
- OnLongClickListener nunca se trigered
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <GridView android:id="@+id/PhoneImageGrid" android:layout_width="fill_parent" android:layout_height="fill_parent" android:numColumns="auto_fit" android:verticalSpacing="12dp" android:horizontalSpacing="12dp" android:columnWidth="90dp" android:stretchMode="columnWidth" android:gravity="center" /> <ImageView android:id="@+id/thumbImage" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:scaleType="centerCrop" />
Quisiera usar setOnLongClick para cada imagen visualizada por el adaptador. Esto funciona bien, sin embargo, al hacer clic largo en el imageView, me gustaría mostrar un ContextMenu con algunos elementos (es decir, haga clic en un imageView, un contextMenu se muestra con algunos elementos: Información de la imagen, enviar esta imagen … ). Por desgracia, no puedo averiguar cómo inflar este menú en el adaptador. (Probablemente no es la buena manera de hacerlo)
Tengo las siguientes líneas en mi actividad principal
_adapter = new ImageAdapter(activity,storedObjects.getAlbums()); imagegrid.setAdapter(_adapter);
Mi adaptador (algunas líneas inútiles eliminadas)
public class ImageAdapter extends BaseAdapter { private Albums albums; private Context context; private LayoutInflater inflater; public ImageAdapter(Context context, Albums albums) { this.albums = albums; this.context = context; inflater = (LayoutInflater)context.getSystemService (Context.LAYOUT_INFLATER_SERVICE); if(albums.getAlbumsListSize() == 0) { Toast.makeText(context, "There is no album to display", Toast.LENGTH_LONG).show(); } } public View getView(final int position, View view, ViewGroup parent) { ViewHolder holder; if (view == null) { holder = new ViewHolder(); view = inflater.inflate(R.layout.galleryitem, null); holder.imageview = (ImageView) view.findViewById(R.id.thumbImage); holder.checkbox = (CheckBox) view.findViewById(R.id.itemCheckBox); holder.textview = (TextView) view.findViewById(R.id.album_name); holder.checkbox.setChecked(true); //Bitmap loadingBM = BitmapFactory.decodeResource(context.getResources(),R.drawable.loading_image); //holder.imageview.setImageBitmap(loadingBM); view.setTag(holder); } else { holder = (ViewHolder) view.getTag(); } holder.imageview.setClickable(true); holder.imageview.setOnLongClickListener(new OnLongClickListener() { public boolean onLongClick(View v) { Log.v(TAG,"onLongClick ok !"); return false; } }); imageDownloader.download(this.context, albums.getAllAlbums().get(position).getThumbnailUri(), holder.imageview); return view; }
Preguntas:
- SetOnLongClickListener funciona correctamente, cuando hago clic en una imagen, mi registro se muestra en logcat, sin embargo, ¿cómo crear un menú para cada imageView?
Aparentemente, sólo puedo anular onCreateContextMenu en mi actividad principal. Supongo que podría pasar cada ImageView a onCreateContextMenu (ContextMenu menú, View v, ContextMenuInfo menuInfo), pero ¿cómo?
Estaría muy agradecido si pudieras ayudarme con esto.
Muchas gracias
Florent Valdelievre
- Usando OnTouchListener y OnLongClickListener interfiere entre sí
- Implementar Drag & Drop en pan de jengibre
- Deshabilitar clic largo para encabezados (o pies de página) en un ListView
- SetOnClickListener y setOnLongClickListener llamada en cuestión de botón único
- Android - ¿Por qué onItemLongClick (...) devuelve un booleano?
- OnLongClickListener no funciona en WebView
- Llamar al método de eliminación en el proveedor de contenido personalizado
- Haga clic en largo Haga clic en span no disparar hasta que se haga clic
En lugar de setOnLongClickListener
en ImageView
, llame a registerForContextMenu
con su GridView
. A continuación, implemente onCreateContextMenu
y onContextItemSelected
.
Aquí hay una ListActivity
simple para mostrarte cómo funciona.
public class GreetingActivity extends ListActivity { private static final String[] mGreetings = { "Hello", "Goodbye" }; private static final String[] mPeople = { "Alice", "Bob", "Charlie" }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mPeople); setListAdapter(adapter); ListView listView = getListView(); registerForContextMenu(listView); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { for (int i = 0; i < mGreetings.length; ++i) { String greeting = mGreetings[i]; menu.add(v.getId(), i, ContextMenu.NONE, "Say " + greeting); } } @Override public boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); int adapterPosition = menuInfo.position; String person = mPeople[adapterPosition]; int menuItemId = item.getItemId(); String greeting = mGreetings[menuItemId]; String msg = String.format("%s, %s!", greeting, person); Toast.makeText(this, msg, Toast.LENGTH_SHORT).show(); return true; } }
Muchas gracias @chiuki, funciona como se esperaba
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ... final GridView imagegrid = (GridView) findViewById(R.id.PhoneImageGrid); registerForContextMenu(imagegrid); storedObjects.storeThumbnailsURI(); _adapter = new ImageAdapter(activity,storedObjects.getAlbums()); imagegrid.setAdapter(_adapter); } @Override public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; Log.v("context menu","context menu"); menu.setHeaderTitle("Context Menu"); menu.add(0, START_SLIDESHOW_ON_THIS_ALBUM, 0, "Start SlideShow for this Album"); menu.add(0, DOWNLOAD_WHOLE_ALBUM, 0, "Download this Album"); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); switch (item.getItemId()) { case START_SLIDESHOW_ON_THIS_ALBUM: selectThisAlbumOnly(info); startSlideShow(); break; case DOWNLOAD_WHOLE_ALBUM: break; } return true; }
En el adaptador, asegúrese de que no tiene ningún setClickable = true
Aclamaciones
Florent
- Cómo utilizar la secuencia de comandos de Perl para la prueba de la aplicación android utilizando eclipse épica?
- La mejor manera de establecer el tamaño del texto?