studio make how example android toast

make - Brindis personalizado en Android: un ejemplo simple



toast en android studio (11)

// Una clase de brindis personalizada donde puede mostrar tostadas personalizadas o predeterminadas según lo desee)

public class ToastMessage { private Context context; private static ToastMessage instance; /** * @param context */ private ToastMessage(Context context) { this.context = context; } /** * @param context * @return */ public synchronized static ToastMessage getInstance(Context context) { if (instance == null) { instance = new ToastMessage(context); } return instance; } /** * @param message */ public void showLongMessage(String message) { Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); } /** * @param message */ public void showSmallMessage(String message) { Toast.makeText(context, message, Toast.LENGTH_LONG).show(); } /** * The Toast displayed via this method will display it for short period of time * * @param message */ public void showLongCustomToast(String message) { LayoutInflater inflater = ((Activity) context).getLayoutInflater(); View layout = inflater.inflate(R.layout.layout_custom_toast, (ViewGroup) ((Activity) context).findViewById(R.id.ll_toast)); TextView msgTv = (TextView) layout.findViewById(R.id.tv_msg); msgTv.setText(message); Toast toast = new Toast(context); toast.setGravity(Gravity.FILL_HORIZONTAL | Gravity.BOTTOM, 0, 0); toast.setDuration(Toast.LENGTH_LONG); toast.setView(layout); toast.show(); } /** * The toast displayed by this class will display it for long period of time * * @param message */ public void showSmallCustomToast(String message) { LayoutInflater inflater = ((Activity) context).getLayoutInflater(); View layout = inflater.inflate(R.layout.layout_custom_toast, (ViewGroup) ((Activity) context).findViewById(R.id.ll_toast)); TextView msgTv = (TextView) layout.findViewById(R.id.tv_msg); msgTv.setText(message); Toast toast = new Toast(context); toast.setGravity(Gravity.FILL_HORIZONTAL | Gravity.BOTTOM, 0, 0); toast.setDuration(Toast.LENGTH_SHORT); toast.setView(layout); toast.show(); } }

Soy nuevo en la programación de Android. ¿Qué es un ejemplo simple que muestra una notificación de brindis personalizada en Android?


Creo que la mayoría de los ejemplos xml personalizados a través de Internet se basan en la misma fuente.

La documentación de Android, que está muy desactualizada en mi opinión. fill_parent no debe usarse más. Prefiero usar wrap_content en combinación con xml.9.png. De esta forma, puede definir el tamaño mínimo de tostarbackground en todo el tamaño de la fuente proporcionada.

Si se requieren brindis más complejos, se debe usar marco o diseño relativo en lugar de LL.

toast.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/points_layout" android:orientation="horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/background" android:layout_gravity="center" android:gravity="center" > <TextView android:id="@+id/points_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:gravity="center" android:layout_margin="15dp" android:text="@+string/points_text" android:textColor="@color/Green" /> </LinearLayout>

background.xml

<?xml version="1.0" encoding="utf-8"?> <nine-patch xmlns:android="http://schemas.android.com/apk/res/android" android:src="@drawable/background_96" android:dither="true"/>

background_96 es background_96.9.png.

Esto no se prueba muy bien, y se aprecian sugerencias :)


Diseño personalizado para brindis, custom_toast.xml :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Custom Toast" android:gravity="center" android:id="@+id/custom_toast_text" android:typeface="serif" android:textStyle="bold" /> </LinearLayout>

Y el método Java (simplemente pase el mensaje de brindis a este método):

public void toast(String message) { Toast toast = new Toast(context); View view = LayoutInflater.from(context).inflate(R.layout.image_custom, null); TextView textView = (TextView) view.findViewById(R.id.custom_toast_text); textView.setText(message); toast.setView(view); toast.setGravity(Gravity.BOTTOM|Gravity.CENTER, 0, 0); toast.setDuration(Toast.LENGTH_LONG); toast.show(); }


Esto es lo que usé

AllMethodsInOne.java

public static Toast displayCustomToast(FragmentActivity mAct, String toastText, String toastLength, String succTypeColor) { final Toast toast; if (toastLength.equals("short")) { toast = Toast.makeText(mAct, tText, Toast.LENGTH_SHORT); } else { toast = Toast.makeText(mAct, tText, Toast.LENGTH_LONG); } View tView = toast.getView(); tView.setBackgroundColor(Color.parseColor("#053a4d")); TextView mText = (TextView) tView.findViewById(android.R.id.message); mText.setTypeface(applyFont(mAct)); mText.setShadowLayer(0, 0, 0, 0); tView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { toast.cancel(); } }); tView.invalidate(); if (succTypeColor.equals("red")) { mText.setTextColor(Color.parseColor("#debe33")); tView.setBackground(mAct.getResources().getDrawable(R.drawable.toast_rounded_red)); // this is to show error message } if (succTypeColor.equals("green")) { mText.setTextColor(Color.parseColor("#053a4d")); tView.setBackground(mAct.getResources().getDrawable(R.drawable.toast_rounded_green)); // this is to show success message } return toast; }

YourFile.java

Mientras llamas solo escribe a continuación.

AllMethodsInOne.displayCustomToast(act, "This is custom toast", "long", "red").show();


Manera simple de personalizar el brindis,

private void MsgDisplay(String Msg, int Size, int Grav){ Toast toast = Toast.makeText(this, Msg, Toast.LENGTH_LONG); TextView v = (TextView) toast.getView().findViewById(android.R.id.message); v.setTextColor(Color.rgb(241, 196, 15)); v.setTextSize(Size); v.setGravity(Gravity.CENTER); v.setShadowLayer(1.5f, -1, 1, Color.BLACK); if(Grav == 1){ toast.setGravity(Gravity.BOTTOM, 0, 120); }else{ toast.setGravity(Gravity.BOTTOM, 0, 10); } toast.show(); }


Puedes descargar el código here .

Paso 1:

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <Button android:id="@+id/btnCustomToast" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Show Custom Toast" /> </RelativeLayout>

Paso 2:

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:gravity="center" android:layout_width="match_parent" android:layout_height="wrap_content"> <ImageView android:id="@+id/custom_toast_image" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@mipmap/ic_launcher"/> <TextView android:id="@+id/custom_toast_message" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="My custom Toast Example Text" /> </LinearLayout>

Paso 3:

import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private Button btnCustomToast; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnCustomToast= (Button) findViewById(R.id.btnCustomToast); btnCustomToast.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Find custom toast example layout file View layoutValue = LayoutInflater.from(MainActivity.this).inflate(R.layout.android_custom_toast_example, null); // Creating the Toast object Toast toast = new Toast(getApplicationContext()); toast.setDuration(Toast.LENGTH_SHORT); // gravity, xOffset, yOffset toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0); toast.setView(layoutValue);//setting the view of custom toast layout toast.show(); } }); } }


Un brindis es por mostrar mensajes por cortos intervalos de tiempo; Entonces, según mi comprensión, le gustaría personalizarlo añadiéndole una imagen y cambiando el tamaño, el color del texto del mensaje. Si eso es todo, desea hacerlo, entonces no hay necesidad de hacer un diseño separado e inflarlo a la instancia de Toast.

La vista predeterminada de Toast contiene un TextView para mostrar mensajes en él. Entonces, si tenemos la referencia de identificación de recursos de ese TextView , podemos jugar con él. Entonces a continuación, ¿qué puedes hacer para lograr esto?

Toast toast = Toast.makeText(this, "I am custom Toast!", Toast.LENGTH_LONG); View toastView = toast.getView(); // This''ll return the default View of the Toast. /* And now you can get the TextView of the default View of the Toast. */ TextView toastMessage = (TextView) toastView.findViewById(android.R.id.message); toastMessage.setTextSize(25); toastMessage.setTextColor(Color.RED); toastMessage.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.ic_fly, 0, 0, 0); toastMessage.setGravity(Gravity.CENTER); toastMessage.setCompoundDrawablePadding(16); toastView.setBackgroundColor(Color.CYAN); toast.show();

En el código anterior puede ver, puede agregar una imagen a TextView a través de setCompoundDrawablesWithIntrinsicBounds(int left, int top, int right, int bottom) cualquier posición relativa a TextView que desee.

Salida:


Use el código siguiente de una tostada personalizada. Puede ser de ayuda.

toast.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/toast_layout_root" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10dp" android:background="#DAAA" > <ImageView android:id="@+id/image" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_marginRight="10dp" /> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="fill_parent" android:textColor="#FFF" /> </LinearLayout>

MainActivity.java

LayoutInflater inflater = getLayoutInflater(); View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root)); ImageView image = (ImageView) layout.findViewById(R.id.image); image.setImageResource(R.drawable.android); TextView text = (TextView) layout.findViewById(R.id.text); text.setText("Hello! This is a custom toast!"); Toast toast = new Toast(getApplicationContext()); toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0); toast.setDuration(Toast.LENGTH_LONG); toast.setView(layout); toast.show();

Y mira los enlaces a continuación también para un Toast personalizado.

Tostada personalizada con reloj analógico

YouTube: Creación de brindis personalizados con botón en Android Studio


Ver el enlace here . Usted encuentra su solución. Y prueba:

Crear una vista de tostada personalizada

Si un mensaje de texto simple no es suficiente, puede crear un diseño personalizado para su notificación de brindis. Para crear un diseño personalizado, defina un diseño de Vista, en XML o en el código de su aplicación, y pase el objeto de Vista raíz al método setView (Ver).

Por ejemplo, puede crear el diseño de la tostada visible en la captura de pantalla a la derecha con el siguiente XML (guardado como toast_layout.xml):

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/toast_layout_root" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10dp" android:background="#DAAA" > <ImageView android:id="@+id/image" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_marginRight="10dp" /> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="fill_parent" android:textColor="#FFF" /> </LinearLayout>

Tenga en cuenta que la ID del elemento LinearLayout es "toast_layout". Debe usar esta identificación para inflar el diseño desde el XML, como se muestra aquí:

LayoutInflater inflater = getLayoutInflater(); View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root)); ImageView image = (ImageView) layout.findViewById(R.id.image); image.setImageResource(R.drawable.android); TextView text = (TextView) layout.findViewById(R.id.text); text.setText("Hello! This is a custom toast!"); Toast toast = new Toast(getApplicationContext()); toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0); toast.setDuration(Toast.LENGTH_LONG); toast.setView(layout); toast.show();

Primero, recupere el LayoutInflater con getLayoutInflater () (o getSystemService ()), y luego infle el diseño desde XML usando inflate (int, ViewGroup). El primer parámetro es el ID del recurso de disposición y el segundo es la Vista raíz. Puede usar este diseño inflado para encontrar más objetos Ver en el diseño, de modo que ahora capture y defina el contenido de los elementos ImageView y TextView. Finalmente, cree una nueva tostada con pan tostado (contexto) y establezca algunas propiedades de la tostada, como la gravedad y la duración. Luego llame a setView (Ver) y páselo por el diseño inflado. Ahora puede mostrar el brindis con su diseño personalizado llamando a show ().

Nota: No use el constructor público para un Toast a menos que vaya a definir el diseño con setView (Ver). Si no tiene un diseño personalizado para usar, debe usar makeText (Context, int, int) para crear el Toast.


Código para el archivo MainActivity.java.

package com.android_examples.com.toastbackgroundcolorchange; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity { Button BT; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); BT = (Button)findViewById(R.id.button1); BT.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast ToastMessage = Toast.makeText(getApplicationContext(),"Change Toast Background color",Toast.LENGTH_SHORT); View toastView = ToastMessage.getView(); toastView.setBackgroundResource(R.layout.toast_background_color); ToastMessage.show(); } }); } }

Código para el archivo de diseño activity_main.xml.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.android_examples.com.toastbackgroundcolorchange.MainActivity" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="CLICK HERE TO SHOW TOAST MESSAGE WITH DIFFERENT BACKGROUND COLOR INCLUDING BORDER" /> </RelativeLayout>

Codifique el archivo de diseño toast_background_color.xml creado en la carpeta res-> layout.

<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" > <stroke android:width="3dp" android:color="#ffffff" ></stroke> <padding android:left="20dp" android:top="20dp" android:right="20dp" android:bottom="20dp" /> <corners android:radius="10dp" /> <gradient android:startColor="#ff000f" android:endColor="#ff0000" android:angle="-90"/> </shape>


PASO 1:

Primero crea un diseño para un brindis personalizado en res/layout/custom_toast.xml :

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/custom_toast_layout_id" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#FFF" android:orientation="horizontal" android:padding="5dp" > <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="fill_parent" android:textColor="#000" /> </LinearLayout>

PASO 2: en el código de Actividad, obtenga la vista personalizada anterior y adjúntela a Toast:

// Get your custom_toast.xml ayout LayoutInflater inflater = getLayoutInflater(); View layout = inflater.inflate(R.layout.custom_toast, (ViewGroup) findViewById(R.id.custom_toast_layout_id)); // set a message TextView text = (TextView) layout.findViewById(R.id.text); text.setText("Button is clicked!"); // Toast... Toast toast = new Toast(getApplicationContext()); toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0); toast.setDuration(Toast.LENGTH_LONG); toast.setView(layout); toast.show();

Para obtener más ayuda, vea cómo creamos Toast personalizado en Android:

developer.android