You are on page 1of 6

Diapo: Activity - Intents

A task is two or more activities chained together.

The < EditText> element defines an editable text field for entering text. It inherits from the Android View class.

Each activity you create must have an entry in


AndroidManifest.xml.

An intent is a type of message that Android components use to communicate with one another.

An explicit intent explicitly specifies the component the intent is targeted at.

You create an explicit intent using


Intent intent = new Intent( this, Target.class);

To start an activity, call startActivity ( intent). If no activities are found, it throws an ActivityNotFoundException.

Use the putExtra() method to add extra information to an intent.

Use the getIntent() method to retrieve the intent that started the activity.

Use the getXXExtra() methods to retrieve extra information associated with the intent. getStringExtra() retrieves a String,
getIntExtra() retrieves an int, and so on.

An activity action describes a standard operational action an activity can perform.

To send a message, use Intent.ACTION_SEND. To create an implicit intent that specifies an action, use
Intent intent = new Intent( action)

To describe the type of data in the intent, use the setType() method.

Android resolves intents based on the named component, action, type of data, and categories specified in the intent. It compares the
contents of the intent with the intent filters in each app’s AndroidManifest.xml.

An activity must have a category of DEFAULT if it is to receive an implicit intent.

The createChooser() method allows you to override the default Android activity chooser dialog. It allows you to specify a title for the
dialog, and doesn’t give the user the option of setting a default activity. If no activities can receive the intent it is passed, it displays a
message.

The createChooser() method returns an Intent.

You retrieve the value of a string resource using


getString(R.string.stringname);

Diapo: Ciclo de vida de las actividades.

Each app runs in its own process by default.

Only the main thread can update the user interface.

Use a Handler to schedule code, or post code to a different thread.

A device configuration change results in the activity being destroyed and re-created.

Your activity inherits the lifecycle methods from the Android Activity class.

If you override any of these methods, you need to call up to the method in the superclass.

onSaveInstanceState(Bundle) enables your activity to save its state before the activity gets destroyed.
You can use the Bundle to restore state inonCreate().

You add values to a Bundle using


bundle.put*("name",value).

You retrieve values from the bundle using


bundle.get*("name").

onCreate() and onDestroy(), deal with the birth and death of the activity.

onRestart(), onStart() and onStop() deal with the visibility of the activity.

onResume() and onPause() deal with when the activity gains and loses the focus.

Diapo: ListViews and Adapters


Sort your ideas for activities into top-level activities, category activities, and detail/ edit activities. Use the category activities to
navigate from the top-level activities to the detail/ edit activities.

A list view displays items in a list. Add it to your layout using the < ListView > element.

Use android:entries in your layout to populate the items in your list views from an array defined in strings.xml.

An adapter acts as a bridge between an AdapterView and a data source. ListViews and Spinners are both types of AdapterView.

An ArrayAdapter is an adapter that works with arrays.

Handle click events on Buttons using android:onClick in the layout code. Handle click events elsewhere by creating a listener and
implementing its click event.

Diapo: Support Librariesand App bars


No hay bullet
Diapo: Fragmentos (No hay)
Un Fragment representa un comportamiento o una parte de la interfaz de usuario en una Activity. Puedes combinar múltiples
fragmentos en una sola actividad para crear una IU multipanel y volver a usar un fragmento en múltiples actividades. Puedes pensar en
un fragmento como una sección modular de una actividad que tiene su ciclo de vida propio, recibe sus propios eventos de entrada y
que puedes agregar o quitar mientras la actividad se esté ejecutando (algo así como una "subactividad" que puedes volver a usar en
diferentes actividades).

Un fragmento siempre debe estar integrado a una actividad y el ciclo de vida del fragmento se ve directamente afectado por el ciclo de
vida de la actividad anfitriona. Por ejemplo, cuando la actividad está pausada, también lo están todos sus fragmentos, y cuando la
actividad se destruye, lo mismo ocurre con todos los fragmentos. Sin embargo, mientras una actividad se está ejecutando (está en el
estado del ciclo de vida reanudada ), puedes manipular cada fragmento de forma independiente; por ejemplo, para agregarlos o
quitarlos. Cuando realizas una transacción de fragmentos como esta, también puedes agregarlos a una pila de actividades administrada
por la actividad; cada entrada de la pila de actividades en la actividad es un registro de la transacción de fragmentos realizada. La pila
de actividades le permite al usuario invertir una transacción de fragmentos (navegar hacia atrás) al presionar el botón Atrás.

Cuando agregas un fragmento como parte del diseño de tu actividad, este se ubica en ViewGroup, dentro de la jerarquía de vistas de la
actividad y el fragmento define su propio diseño de vista. Puedes insertar un fragmento en el diseño de tu actividad declarando el
fragmento en el archivo de diseño de la actividad como elemento <fragment> o agregándolo a un ViewGroup existente desde el
código de tu aplicación. Sin embargo, no es necesario que un fragmento forme parte del diseño de la actividad; también puedes usar
un fragmento con su IU propia, como un trabajador invisible para la actividad.

Este documento describe cómo crear tu aplicación para usar fragmentos, incluido cómo los fragmentos pueden mantener su estado
cuando se los agrega a la pila de actividades de la actividad, cómo pueden compartir eventos con la actividad y con otros fragmentos
en la actividad, cómo pueden contribuir con la barra de acciones de la actividad, etc.

Filosofía de diseño
Debes diseñar cada fragmento como un componente modular y reutilizable de la actividad. Como cada fragmento define su propio
diseño y su propio comportamiento con sus propios callbacks del ciclo de vida, puedes incluir un fragmento en múltiples actividades;
por lo tanto, debes diseñarlo para volver a utilizarlo y evitar la manipulación directa de un fragmento desde otro fragmento. Esto es
muy importante porque un fragmento modular te permite cambiar tus combinaciones de fragmentos para diferentes tamaños de
pantalla. Cuando diseñas tu aplicación para que admita tablets y teléfonos, puedes reutilizar tus fragmentos en diferentes
configuraciones de diseño para optimizar la experiencia del usuario en función del espacio de pantalla disponible. Por ejemplo, en un
teléfono, podría ser necesario separar los fragmentos para proporcionar una IU de panel único cuando no quepa más de uno en la
misma actividad.

Crear un fragmento
Para crear un fragmento, debes crear una subclase Fragment (o una subclase existente de ella). La clase Fragment tiene un código que
se asemeja bastante a una Activity. Contiene métodos callback similares a los de una actividad, como onCreate(), onStart(),
onPause() y onStop(). De hecho, si estás convirtiendo una aplicación de Android existente para utilizar fragmentos, deberías
simplemente trasladar código de los métodos callback de tu actividad a los métodos callback respectivos de tu fragmento.

Generalmente, debes implementar al menos los siguientes métodos del ciclo de vida:

onCreate()
El sistema lo llama cuando crea el fragmento. En tu implementación, debes inicializar componentes esenciales del fragmento
que quieres conservar cuando el fragmento se pause o se detenga y luego se reanude

onCreateView()
El sistema lo llama cuando el fragmento debe diseñar su interfaz de usuario por primera vez. Para diseñar una IU para tu
fragmento, debes devolver una View desde este método que será la raíz del diseño de tu fragmento. Puedes devolver nulo su el
fragmento no proporciona una IU.
onPause()
El sistema llama a este método como el primer indicador de que el usuario está abandonando el fragmento (aunque no siempre
significa que el fragmento se esté destruyendo). Generalmente este es el momento en el que debes confirmar los cambios que
deban conservarse más allá de la sesión de usuario actual (porque es
posible que el usuario no vuelva).
La mayoría de las aplicaciones deben implementar al menos estos tres métodos para cada fragmento, pero hay muchos otros métodos
callback que también debes usar para manipular varias fases del ciclo de vida del fragmento. Todos los métodos callback del ciclo de
vida se discuten en más detalle más adelante en la sección Manipulación del ciclo de vida del fragmento.

Existen también algunas subclases que quizá desees extender, en lugar de la clase de base Fragment:

DialogFragment
Muestra un diálogo flotante. Usar esta clase para crear un diálogo es una buena alternativa al uso de métodos del asistente de
diálogos en la clase Activity, ya que puedes incorporar un diálogo del fragmento en la pila de actividades de fragmentos
administrados por la actividad, lo que le permite al usuario volver a un fragmento descartado.
ListFragment
Muestra una lista de elementos administrados por un adaptador (como un SimpleCursorAdapter, al igual que ListActivity.
Proporciona varios métodos para administrar una vista de lista, como el callback onListItemClick() para manipular eventos
de clic.
PreferenceFragment
Muestra una jerarquía de objetos Preference en forma de lista, al igual que PreferenceActivity. Esto resulta útil para crear
una actividad "configuración" para tu aplicación.

Diapo: Recycler View–Card View

Card views and recycler views have their own Support Libraries.

Add a card view to a layout using the <android.support.v7.widget.CardView> element.

Give the card view rounded corners using the cardCornerRadius attribute. This requires a namespace of "http://schemas.android.com/
apk/ res-auto".

Give the card view a drop shadow using the cardElevation attribute. This requires a namespace of "http:// schemas.android.com/ apk/
res-auto".

Recycler views work with adapters that are subclasses of RecyclerView.Adapter.

When you create your own RecyclerView.Adapter, you must define the view holder and implement the onCreateViewHolder(),
onBindViewHolder(), and getItemCount() methods.

You add a recycler view to a layout using the <android.support.v7.widget.RecyclerView> element. You give it a scrollbar using the
android:scrollbars attribute.

Use a layout manager to specify how items in a recycler view should be arranged. A LinearLayoutManager arranges items in a linear
list, a GridLayoutManager arranges items in a grid, and a StaggeredGridLayoutManager arranges items in a staggered grid
Diapo: NavigationDrawer
Use a navigation drawer if you want to provide the user with a large number of shortcuts, or group them into sections.

Create a navigation drawer by adding a drawer layout to your activity’s layout. The drawer layout’s first element needs to be a view
that defines the activity’s main content, usually a layout containing a Toolbar and FrameLayout

Its second element defines the contents of the drawer, usually a NavigationView.

The NavigationView comes from the Design Support Library. It controls most of the drawer’s behavior.

You add a header to your drawer by creating a layout for it, and adding the header’s resource ID to the navigation view’s
headerLayout attribute.

You add items to the drawer by creating a menu resource, and adding the menu’s resource ID to the navigation view’s menu attribute.

Add items to the menu resource in the order in which you want them to appear in the drawer.

If you want to highlight which item in the drawer the user selects, add the menu items to a group and set the group’s
checkableBehavior attribute to "single".

Use an ActionBarDrawerToggle to display a “burger” icon in the activity’s toolbar. This provides a visual sign that the activity has a
navigation drawer. Clicking on it opens the drawer.

Respond to the user clicking on items in the drawer by making your activity implement the
NavigationView.OnNavigationItemSelectedListener interface. Register the activity with the navigation view as a listener, then
implement the onNavigationItemSelected() method.

Close the navigation drawer using the DrawerLayout closeDrawer() method

Diapo: SQLite and Android

Android uses SQLite as its backend database to persist data.

The SQLiteDatabase class gives you access to the SQLite database.

A SQLite helper lets you create and manage SQLite databases. You create a SQLite helper by extending the SQLiteOpenHelper
class.

You must implement the SQLiteOpenHelper onCreate() and onUpgrade() methods.

The database gets created the first time it needs to be accessed. You need to give the database a name and version number, starting at
1. If you don’t give the database a name, it will just get created in memory.

The onCreate() method gets called when the database first gets created.

The onUpgrade() method gets called when the database needs to be upgraded.

Execute SQL using the SQLiteDatabase execSQL (String) method.

Add records to tables using the insert() method

You might also like