¿Botón en la tostada de encargo de Android?
¿Es posible tener un botón en un Toast?
En teoría, sí, porque puedes crear un Toast personalizado desde un diseño en XML, pero traté de poner un botón en él y no pude conseguirlo para registrar el clic. ¿Alguien logró hacer algo así?
- Mostrar una imagen en un brindis
- Contabilización del mensaje Toast de un hilo
- ¿Cómo mostrar un Toast dentro de un Handler / hilo?
- Android: Notificación personalizada de brindis hereda toast predeterminado
- Ejecutar la búsqueda desde la barra de acción
- Eliminar "Gracias. Su artículo aparecerá en breve. "Tostada de aparecer después de la compra de InApp
- El tostado androide no se ajusta al texto
- Cómo establecer el tiempo de visualización de Toast menos de Toast.LENGTH_SHORT
- Detección de mensajes de tostadas
- Tostadas no aparecen en UnCaughtExceptionHandler
- Comparando dos veces en android
- ¿Por qué Toast.makeText y no Toast nuevo
- Tostada no se muestra en el Samsung Galaxy S3 (última actualización 4.1.2)
No se puede hacer clic en un brindis. No es posible capturar un clic dentro de un mensaje de brindis. Usted necesitará construir un diálogo para eso. Consulte Crear diálogos para obtener más información.
La API en la clase Toast indica que un brindis nunca recibirá el foco y porque un brindis no es una vista, no hay un mensaje onClick. Supongo que por lo tanto childs de un Toast no se puede hacer clic también.
Un tostado no puede contener un botón. Excepto que la aplicación de gmail y la aplicación de la galería en los jelly beans tienen un semi tostado que contiene un botón, aquí es cómo Google lo hizo
https://gist.github.com/benvd/4090998
Supongo que esto responde a su pregunta.
Snippet muestra la implementación de un brindis personalizado que:
- Tienen una interfaz similar a la de la clase
Toast
original - Se puede utilizar como
Dialog
(tiene botones que se pueden hacer clic como la aplicación de Gmail) - Tener la posibilidad de establecer la
length
enmillis
- Tener la posibilidad de establecer mostrar y cancelar la animación
- Vive solo con
Activity
inicializada
Limitaciones actuales:
- No se admiten cambios en la orientación de la pantalla
Uso:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //... View toastView = new View(getBaseContext()); //init your toast view ActivityToast toast = new ActivityToast(this, toastView); //set toast Gravity ( Gravity.BOTTOM | Gravity.FILL_HORIZONTAL by default) toast.setGravity(Gravity.CENTER); toast.setLength(10000); //set toast show duration to 10 seconds (2 seconds by default) Animation showAnim; // init animation Animation.AnimationListener showAnimListener; //init anim listener toast.setShowAnimation(showAnim); toast.setShowAnimationListener(showAnimListener); Animation cancelAnim; // init animation Animation.AnimationListener cancelAnimListener; //init anim listener toast.setCancelAnimation(showAnim); toast.setCancelAnimationListener(showAnimListener); toast.show(); //show toast view toast.isShowing(); // check if toast is showing now toast.cancel(); //cancel toast view toast.getView(); //get toast view to update it or to do something .. }
Fuentes
import android.app.Activity; import android.os.Handler; import android.support.annotation.NonNull; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.widget.FrameLayout; public class ActivityToast { public static final long LENGTH_SHORT = 2000; public static final long LENGTH_LONG = 3000; public static final int DEFAULT_ANIMATION_DURATION = 400; private final Activity mActivity; private FrameLayout.LayoutParams mLayoutParams; private Handler mHandler = new Handler(); private ViewGroup mParent; private FrameLayout mToastHolder; private View mToastView; private Animation mShowAnimation; private Animation mCancelAnimation; private long mLength = LENGTH_SHORT; private Animation.AnimationListener mShowAnimationListener; private Animation.AnimationListener mCancelAnimationListener; private boolean mIsAnimationRunning; private boolean mIsShown; /** * @param activity Toast will be shown at top of the widow of this Activity */ public ActivityToast(@NonNull Activity activity, View toastView) { mActivity = activity; mParent = (ViewGroup) activity.getWindow().getDecorView(); mToastHolder = new FrameLayout(activity.getBaseContext()); mLayoutParams = new FrameLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM | Gravity.FILL_HORIZONTAL ); mToastHolder.setLayoutParams(mLayoutParams); mShowAnimation = new AlphaAnimation(0.0f, 1.0f); mShowAnimation.setDuration(DEFAULT_ANIMATION_DURATION); mShowAnimation.setAnimationListener(mHiddenShowListener); mCancelAnimation = new AlphaAnimation(1.0f, 0.0f); mCancelAnimation.setDuration(DEFAULT_ANIMATION_DURATION); mCancelAnimation.setAnimationListener(mHiddenCancelListener); mToastView = toastView; mToastHolder.addView(mToastView); mToastHolder.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) { cancel(); } return false; } }); } public void show() { if (!isShowing()) { mParent.addView(mToastHolder); mIsShown = true; if (mShowAnimation != null) { mToastHolder.startAnimation(mShowAnimation); } else { mHandler.postDelayed(mCancelTask, mLength); } } } public void cancel() { if (isShowing() && !mIsAnimationRunning) { if (mCancelAnimation != null) { mToastHolder.startAnimation(mCancelAnimation); } else { mParent.removeView(mToastHolder); mHandler.removeCallbacks(mCancelTask); mIsShown = false; } } } public boolean isShowing() { return mIsShown; } /** * Pay attention that Action bars is the part of Activity window * * @param gravity Position of view in Activity window */ public void setGravity(int gravity) { mLayoutParams.gravity = gravity; if (isShowing()) { mToastHolder.requestLayout(); } } public void setShowAnimation(Animation showAnimation) { mShowAnimation = showAnimation; } public void setCancelAnimation(Animation cancelAnimation) { mCancelAnimation = cancelAnimation; } /** * @param cancelAnimationListener cancel toast animation. Note: you should use this instead of * Animation.setOnAnimationListener(); */ public void setCancelAnimationListener(Animation.AnimationListener cancelAnimationListener) { mCancelAnimationListener = cancelAnimationListener; } /** * @param showAnimationListener show toast animation. Note: you should use this instead of * Animation.setOnAnimationListener(); */ public void setShowAnimationListener(Animation.AnimationListener showAnimationListener) { mShowAnimationListener = showAnimationListener; } public void setLength(long length) { mLength = length; } public View getView() { return mToastView; } private Runnable mCancelTask = new Runnable() { @Override public void run() { cancel(); } }; private Animation.AnimationListener mHiddenShowListener = new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { if (mShowAnimationListener != null) { mShowAnimationListener.onAnimationStart(animation); } mIsAnimationRunning = true; } @Override public void onAnimationEnd(Animation animation) { mHandler.postDelayed(mCancelTask, mLength); if (mShowAnimationListener != null) { mShowAnimationListener.onAnimationEnd(animation); } mIsAnimationRunning = false; } @Override public void onAnimationRepeat(Animation animation) { if (mShowAnimationListener != null) { mShowAnimationListener.onAnimationRepeat(animation); } } }; private Animation.AnimationListener mHiddenCancelListener = new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { if (mCancelAnimationListener != null) { mCancelAnimationListener.onAnimationStart(animation); } mIsAnimationRunning = true; } @Override public void onAnimationEnd(Animation animation) { mParent.removeView(mToastHolder); mHandler.removeCallbacks(mCancelTask); if (mCancelAnimationListener != null) { mCancelAnimationListener.onAnimationEnd(animation); } mIsAnimationRunning = false; mIsShown = false; } @Override public void onAnimationRepeat(Animation animation) { if (mCancelAnimationListener != null) { mCancelAnimationListener.onAnimationRepeat(animation); } } }; }
Mi post original en github
Publicar que muestra la implementación del diseño personalizado en esta publicación
Una vista personalizada pasada a un brindis puede contener cualquier cosa; Sin embargo, los brindis no pueden recibir ningún evento táctil, por lo que ningún componente que utilice eventos táctiles funcionará en una tostada común (botones, botones de radio, etc.). La única opción que tienes es crear una vista personalizada con un botón en ella y añadirla a tu diseño. Hay muchos ejemplos de cómo hacer esto y algunas bibliotecas que puede comprobar para ver cómo otras personas lo están haciendo.
UndoBar
MessageBar
UndoBar de Nurik
Por supuesto que también son bienvenidos a usar la biblioteca de SuperToasts que puse juntos sin embargo puede ser un poco exceso para un uso. La forma en que lo hago se describe en la clase SuperActivityToast .
Puedes intentar SuperToast en este caso. Puede crear brindis con el botón. Tiene característica de encargo de la duración, fondo colorido, fuentes coloridas, fuentes de encargo, efecto animado. Espero que lo disfrutes
Utilice un cuadro de alerta, si desea agregar un botón :-). Estos son algunos ejemplos Cuadros de diálogo en Android
Creación de una ventana de superposición del sistema (siempre en la parte superior)
Esto es lo que sugiere que se puede hacer, también necesito botones en un brindis por lo que todavía tengo que hacer mi propia aplicación. Si encuentro más, lo añadiré a mi publicación
Deberías usar una Snackbar
. Está en la última biblioteca de soporte de android (en el momento de la respuesta) y es compatible con los niveles de api más antiguos. Es mucho más fácil de implementar que un Dialog
o View
personalizada y tiene la capacidad de tener un botón a diferencia de un Toast
.
- Descargue la
Android Support Library
desdeExtras
en elSDK Manager
delSDK Manager
(revisión 22.2.1 o posterior). - En
build.gradle
agregue esto a las dependencias de clase:com.android.support:design:22.2.0
. -
Implementar:
Snackbar.make(this.findViewById(android.R.id.content), "Toast Message", Snackbar.LENGTH_LONG) .setAction("Click here to activate action", onClickListener) .setActionTextColor(Color.RED) .show;
Y eso es todo. No github proyectos y la aplicación es muy similar a Toast
. Lo usé en uno de mis proyectos y funciona muy bien.
- Objeto no bloqueado por subproceso antes de notificar () en onPostExecute
- Esta visión no está restringida