You are on page 1of 8

1

3.3. Example for a custom adapter


The following code shows an implementation of a custom adapter. This adapter
assumes that you have two png files (no.png and yes.png) in one of your
res/drawable folders. The coding inflates an XML layout file, finds the relevant views
in the layout and sets their content based on the input data.

package de.vogella.android.listactivity;
import
import
import
import
import
import
import

android.content.Context;
android.view.LayoutInflater;
android.view.View;
android.view.ViewGroup;
android.widget.ArrayAdapter;
android.widget.ImageView;
android.widget.TextView;

public class MySimpleArrayAdapter extends ArrayAdapter<String> {


private final Context context;
private final String[] values;
public MySimpleArrayAdapter(Context context, String[] values) {
super(context, R.layout.rowlayout, values);
this.context = context;
this.values = values;
}
@Override
public View getView(int position, View convertView, ViewGroup
parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.rowlayout, parent,
false);
TextView textView = (TextView) rowView.findViewById(R.id.label);
ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
textView.setText(values[position]);
// change the icon for Windows and iPhone
String s = values[position];
if (s.startsWith("iPhone")) {
imageView.setImageResource(R.drawable.no);
} else {
imageView.setImageResource(R.drawable.ok);
}
return rowView;
}
}

3.4. Updating the data model from the adapter


The row can also contain views which interact with the underlying data model via the
adapter. For example, you can have a Checkbox in your row layout and if the
Checkbox is selected, the underlying data is changed.

Toasts
Un toast es un mensaje que se muestra en pantalla durante unos segundos al usuario para
luego volver a desaparecer automticamente sin requerir ningn tipo de actuacin por su
parte, y sin recibir el foco en ningn momento (o dicho de otra forma, sin interferir en las
acciones que est realizando el usuario en ese momento). Aunque son personalizables,
aparecen por defecto en la parte inferior de la pantalla, sobre un rectngulo gris ligeramente
translcido. Por sus propias caractersticas, este tipo de notificaciones son ideales para
mostrar mensajes rpidos y sencillos al usuario, pero por el contrario, al no requerir
confirmacin por su parte, no deberan utilizarse para hacer notificaciones demasiado
importantes.
Su utilizacin es muy sencilla, concentrndose toda la funcionalidad en la clase Toast. Esta clase
dispone de un mtodo esttico makeText() al que deberemos pasar como parmetro el contexto de la
actividad, el texto a mostrar, y la duracin del mensaje, que puede tomar los valores LENGTH_LONG o
LENGTH_SHORT, dependiendo del tiempo que queramos que la notificacin aparezca en pantalla. Tras
obtener una referencia al objeto Toast a travs de este mtodo, ya slo nos quedara mostrarlo en
pantalla mediante el mtodo show().
Vamos a construir una aplicacin de ejemplo para demostrar el funcionamiento de este tipo de
notificaciones. Y para empezar vamos a incluir un botn que muestre un toast bsico de la forma que
acabamos de describir:
1 btnDefecto.setOnClickListener(new OnClickListener() {
2

@Override

public void onClick(View arg0) {


Toast toast1 =

Toast.makeText(getApplicationContext(),

"Toast por defecto", Toast.LENGTH_SHORT);

6
7

toast1.show();

8
9

10});
Si ejecutamos esta sencilla aplicacin en el emulador y pulsamos el botn que acabamos de aadir
veremos como en la parte inferior de la pantalla aparece el mensaje Toast por defecto, que tras varios
segundos desaparecer automticamente.

tambin podemos personalizarlo un poco cambiando su posicin en la pantalla. Para esto


utilizaremos el mtodo setGravity(), al que podremos indicar en qu zona deseamos que
aparezca la notificacin. La zona deberemos indicarla con alguna de las constantes definidas
en la clase Gravity: CENTER, LEFT, BOTTOM, o con alguna combinacin de stas.

Para nuestro ejemplo vamos a colocar la notificacin en la zona central izquierda de la pantalla. Para ello,
aadamos un segundo botn a la aplicacin de ejemplo que muestre un toast con estas caractersticas:
1 btnGravity.setOnClickListener(new OnClickListener() {
2

@Override

public void onClick(View arg0) {


Toast toast2 =

Toast.makeText(getApplicationContext(),

"Toast con gravity", Toast.LENGTH_SHORT);

6
7

toast2.setGravity(Gravity.CENTER|Gravity.LEFT,0,0);

8
9

toast2.show();

10

11
12});

Si volvemos a ejecutar la aplicacin y pulsamos el nuevo botn veremos como el toast aparece en la zona
indicada de la pantalla:

Si esto no es suficiente y necesitamos personalizar por completo el aspecto de la


notificacin, Android nos ofrece la posibilidad de definir un layout XML propio para
toast, donde podremos incluir todos los elementos necesarios para adaptar la
notificacin a nuestras necesidades. para nuestro ejemplo vamos a definir un layout
sencillo, con una imagen y una etiqueta de texto sobre un rectngulo gris:
1 <?xml version="1.0" encoding="utf-8"?>
2 <LinearLayout
3

xmlns:android="http://schemas.android.com/apk/res/android"

android:id="@+id/lytLayout"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:orientation="horizontal"

android:background="#555555"

android:padding="5dip" >

10
11

<ImageView android:id="@+id/imgIcono"

12

android:layout_height="wrap_content"

13

android:layout_width="wrap_content"

14

android:src="@drawable/marcador" />

15
16

<TextView android:id="@+id/txtMensaje"

17

android:layout_width="wrap_content"

18

android:layout_height="wrap_content"

19

android:layout_gravity="center_vertical"

20

android:textColor="#FFFFFF"

21

android:paddingLeft="10dip" />

22
23</LinearLayout>

Guardaremos este layout con el nombre toast_layout.xml, y como siempre lo


colocaremos en la carpeta res\layout de nuestro proyecto.
Para asignar este layout a nuestro toast tendremos que actuar de una forma algo diferente a las
anteriores. En primer lugar deberemos inflar el layout mediante un objeto LayoutInflater, como ya
vimos en varias ocasiones al tratar los artculos de interfaz grfica. Una vez construido el layout
modificaremos los valores de los distintos controles para mostrar la informacin que queramos. En

nuestro caso, tan slo modificaremos el mensaje de la etiqueta de texto, ya que la imagen ya la
asignamos de forma esttica en el layout XML mediante el atributo android:src. Tras esto, slo nos
quedar establecer la duracin de la notificacin con setDuration() y asignar el layout personalizado
al toast mediante el mtodo setView(). Veamos cmo quedara todo el cdigo incluido en un tercer
botn de ejemplo:
1

btnLayout.setOnClickListener(new OnClickListener() {
@Override

public void onClick(View arg0) {

Toast toast3 = new Toast(getApplicationContext());

4
5

LayoutInflater inflater = getLayoutInflater();

View layout = inflater.inflate(R.layout.toast_layout,

(ViewGroup) findViewById(R.id.lytLayout));

8
9
10
11

TextView txtMsg =
(TextView)layout.findViewById(R.id.txtMensaje);
txtMsg.setText("Toast Personalizado");

12
13

toast3.setDuration(Toast.LENGTH_SHORT);

14

toast3.setView(layout);

15

toast3.show();

16
17

}
});

Si ejecutamos ahora la aplicacin de ejemplo y pulsamos el nuevo botn, veremos como nuestro toast

aparece con la estructura definida en nuestro layout personalizado.

Como podis comprobar, mostrar notificaciones de tipo Toast en nuestras aplicaciones Android es algo de
lo ms sencillo, y a veces resultan un elemento de lo ms interesante para avisar al usuario de
determinados eventos.

Key classes
1. Toast
A toast provides simple feedback about an operation in a small popup. It only fills the amount
of space required for the message and the current activity remains visible and interactive. For
example, navigating away from an email before you send it triggers a "Draft saved" toast to let
you know that you can continue editing later. Toasts automatically disappear after a timeout.

The Basics
First, instantiate a Toast object with one of the makeText() methods. This method takes
three parameters: the application Context, the text message, and the duration for the toast. It
returns a properly initialized Toast object. You can display the toast notification with show(),
as shown in the following example:
Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();

7
This example demonstrates everything you need for most toast notifications. You should rarely
need anything else. You may, however, want to position the toast differently or even use your
own layout instead of a simple text message. The following sections describe how you can do
these things.
You can also chain your methods and avoid holding on to the Toast object, like this:
Toast.makeText(context, text, duration).show();

Positioning your Toast


A standard toast notification appears near the bottom of the screen, centered horizontally. You
can change this position with the setGravity(int, int, int) method. This accepts
three parameters: a Gravity constant, an x-position offset, and a y-position offset.
For example, if you decide that the toast should appear in the top-left corner, you can set the
gravity like this:
toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);

If you want to nudge the position to the right, increase the value of the second parameter. To
nudge it down, increase the value of the last parameter.

Creating a Custom Toast View


If a simple text message isn't enough, you can create a customized layout for your toast
notification. To create a custom layout, define a View layout, in XML or in your application code,
and pass the root View object to the setView(View) method.
For example, you can create the layout for the toast visible in the screenshot to the right with the
following XML (saved as 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="8dp"
android:background="#DAAA"
>
<ImageView android:src="@drawable/droid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="8dp"
/>
<TextView android:id="@+id/text"
android:layout_width="wrap_content"

8
android:layout_height="wrap_content"
android:textColor="#FFF"
/>
</LinearLayout>

Notice that the ID of the LinearLayout element is "toast_layout_root". You must use this ID to
inflate the layout from the XML, as shown here:
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
(ViewGroup)
findViewById(R.id.toast_layout_root));
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("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();

First, retrieve the LayoutInflater with getLayoutInflater() (or


getSystemService()), and then inflate the layout from XML using inflate(int,
ViewGroup). The first parameter is the layout resource ID and the second is the root View. You
can use this inflated layout to find more View objects in the layout, so now capture and define the
content for the ImageView and TextView elements. Finally, create a new Toast with
Toast(Context) and set some properties of the toast, such as the gravity and duration. Then
call setView(View) and pass it the inflated layout. You can now display the toast with your
custom layout by calling show().
Note: Do not use the public constructor for a Toast unless you are going to define the layout with
setView(View). If you do not have a custom layout to use, you must use
makeText(Context, int, int) to create the Toast.

You might also like