Taller Desarrollo Mobile Tecnólogo Informática - 6to Semestre Montevideo
UI INTENT Desarrollo Mobile
Agenda UI Layout Fragments Widget Tool Box Adapters Intent - Broadcast Receiver Internet Resources
Repaso Desarrollo Mobile
Repaso Activity Son componentes que representan a una pantalla. Cada pantalla está asociada a una o más activity. public class MainActivity extends Activity { @Override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); }
Repaso Manifest Es un archivo XML donde se definen las características principales de la aplicación. Declaración de actividades Declaración de permisos Versión de SDK
Repaso Recursos Es todo aquello que utiliza la aplicación que no forma parte del código fuente. Imagenes,videos, archivos de audio,textos, menús y layout. Se encuentra dentro de la carpeta res y se acceden mediante un identificador.
Repaso Términos y Conceptos Tamaño de pantalla Densidad de pantalla Orientación Resolución Densidad Independiente de pixel (dp)
Repaso Usabilidad Facilidad con que el usuario puede utilizar la aplicación Considerar: Lugar de acceso Iluminación Tamaños de pantalla Ubicación de controles (botones, cajas de texto, etc.) Movimiento y rotación Performance
Repaso Usabilidad Elementos clave para usabilidad mobile tiempo navegación pulgar-friendly visibilidad simplicidad evitar ingresos de mucha información seleccionar vs ingresar
Repaso Usabilidad
UI Desarrollo Mobile
Layout Son componentes invisibles que determinan la disposición de las vistas en una pantalla, pueden ser creados por código o en archivos XML.
Layout Cada Archivo XML layout es compilado en un recurso layout R.layout.<layout_file_name> Un recurso de layout es cargado con setcontentview(r.layout.<layout_file_name>) public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main_layout); }
Layout
Layout
Layout XML <?xml version= 1.0 encoding= utf-8?> <LinearLayout xmlns:android=./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= Text /> <EditText android:layout_width= match_parent android:layout_height= wrap_content android:text= Text /></LinearLayout> CÓDIGO LinearLayout ll = new LinearLayout(this); ll.setorientation(linearlayout.vertical); TextView mytextview = new TextView(this); EditText myedittext = new EditText(this); mytextview.settext( Enter Text Below ); myedittext.settext( Text Goes Here! ); int lheight = LinearLayout.LayoutParams.MATCH_PARENT; int lwidth = LinearLayout.LayoutParams.WRAP_CONTENT; ll.addview(mytextview, new LinearLayout.LayoutParams(lHeight, lwidth)); ll.addview(myedittext, new LinearLayout.LayoutParams(lHeight, lwidth)); setcontentview(ll);
Layout
Layout
Layout <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/androi d" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/label" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="type here:"> </TextView> <EditText android:id="@+id/entry" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/label" android:background="@android:drawable/editbox_backgro und"> </EditText> <Button android:id="@+id/ok" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignparentright="true" android:layout_below="@+id/entry" android:layout_marginleft="10dip" android:text="ok"> </Button> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_aligntop="@+id/ok" android:layout_toleftof="@+id/ok" android:text="cancel"> </Button> </RelativeLayout>
Layout <?xml version="1.0" encoding="utf-8"?> <AbsoluteLayout xmlns:android="http://schemas.android.com/ apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_x="42dp" android:layout_y="62dp" android:text="button"> </Button> <RadioButton android:id="@+id/radiobutton1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_x="171dp" android:layout_y="318dp" android:text="radiobutton"> </RadioButton> </AbsoluteLayout>
Layout <?xml version= 1.0 encoding= utf-8?> <merge xmlns:android= http://schemas.android.com/apk/res/andr oid > <ImageView android:id= @+id/myimageview android:layout_width= match_parent android:layout_height= match_parent android:src= @drawable/myimage /> <TextView android:id= @+id/mytextview android:layout_width= match_parent android:layout_height= wrap_content android:text= @string/hello android:gravity= center_horizontal android:layout_gravity= bottom /> </merge> <?xml version= 1.0 encoding= utf-8?> <LinearLayout xmlns:android= http://schemas.android.com/apk/res/andr oid android:orientation= vertical android:layout_width= match_parent android:layout_height= match_parent > <include android:id= @+id/my_action_bar layout= @layout/actionbar /> <include android:id= @+id/my_image_text_layout layout= @layout/image_text_layout /> </LinearLayout>
Layout
Fragment Es una sección de una actividad, tiene su propio ciclo de vida, recibe sus propios eventos de entrada, y se añadir o quitar mientras la actividad se está ejecutando. Un fragmento puede ser reutilizado en más de una actividad. public class ArticleFragment extends Fragment { @Override public View oncreateview(layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) { return inflater.inflate(r.layout.some, container, false); } }
Fragment public class MyActivity extends FragmentActivity public class MySkeletonFragment extends Fragment { @Override public View oncreateview(layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) { // Create, or inflate the Fragment s UI, and return it. // If this Fragment has no UI then return null. return inflater.inflate(r.layout.my_fragment, container, false); } } FragmentManager fragmentmanager = getfragmentmanager(); <?xml version= 1.0 encoding= utf-8?> <LinearLayout xmlns:android= http://schemas.android.com/apk/res/android android:orientation= horizontal android:layout_width= match_parent android:layout_height= match_parent > <fragment android:name= com.paad.weatherstation.mylistfragment android:id= @+id/my_list_fragment android:layout_width= match_parent android:layout_height= match_parent android:layout_weight= 1 /> <fragment android:name= com.paad.weatherstation.detailsfragment android:id= @+id/details_fragment android:layout_width= match_parent Introducing Fragments x 121 android:layout_height= match_parent android:layout_weight= 3 /></LinearLayout>
Fragment
Fragment Dialog Fragment ListFragment WebViewFragment
Dialog Son ventanas pequeñas que se colocan por encima de la actividad actual, la cual pierde el foco. Usualmente utilizados para notificaciones o acciones simples. AlertDialog ProgressDialog DatePickerDialog TimePickerDialog
Dialog AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setmessage("are you sure you want to exit?").setcancelable(false).setpositivebutton("yes", new DialogInterface.OnClickListener() { public void onclick(dialoginterface dialog, int id) { MyActivity.this.finish(); } }).setnegativebutton("no", new DialogInterface.OnClickListener() { public void onclick(dialoginterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create();
Custom Dialog <LinearLayout xmlns:android="http://schemas.android.com/apk/res /android" android:id="@+id/layout_root" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10dp" > <ImageView android:id="@+id/image" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_marginright="10dp" /> </LinearL ayout> Context mcontext = getapplicationcontext(); Dialog dialog = new Dialog(mContext); dialog.setcontentview(r.layout.custom_dialog); dialog.settitle("custom Dialog"); ImageView image = (ImageView) dialog.findviewbyid(r.id.image); image.setimageresource(r.drawable.android);
View View Son los componentes de la interfaz del usuario, ejemplo: TextView, EditText,Button, Checkbox, etc. View Group Son vistas especiales que contienen otras vistas (DatePicker, Gallery, ListView, ScrollView, etc.) ViewStub Es una vista invisible y sin tamaño que se usa de forma lazily inflate en tiempo de ejecución.
Widget ToolBox TextView EditText AutoCompleteTextView MultiAutoCompleteTextView Button ImageButton ToogleButton CheckBox RadioButton ListView WebView
Custom View Modificar o extender Modificar o extender Combinar Crear
Lint
Adapters Son utilizados para ligar datos para ser mostrados a View Groups que extiendan de AdapterView tales como ListView o Gallery. ArrayAdapter SimpleCursorAdapter
Intents Son mensajes que provocan notificaciones o cambios de estado. Cumplen la función de unir componentes dentro de la misma aplicación o diferentes aplicaciones, el uso más común es navegar entre actividades. Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse( tel:555-2368 )); startactivity(intent);
Intents Explícitos: Si se establece un destinatario, se le envía un mensaje directamente(dentro de la aplicación). Implícitos: Si no se establece un destinatario, se debe incluir suficiente información para que Android determine el mejor componente candidato para ejecutar el Intent(Fuera de la aplicación). Para buscar el mejor candidato, se utilizan los Intent-filters
Intents
Intents Estructura Action: Determina la acción que genera (ACTION_VIEW, ACTION_EDIT, etc.) Data: Contiene los datos que la acción debe operar. Son expresados en forma de URI ACTION_VIEW: content://contacts/people/1 ACTION_DIAL: tel://55555555 ACTION_DIAL: content://contacts/people/2
Intents Atributos adicionales Category: Ofrece información adicional sobre el tipo de componente que debe capturar el Intent. Type: Tipo MIME de los datos del Intent. Es opcional. Component: Indica qué componente especificado en el Manifest realizará la acción del Intent. Si se especifica, se entregará a una instancia de esa clase, si no Android buscará el componente que mejor considere. Extras: Información adicional, en pares clave / valor.
Intents Acciones nativas ACTION_ANSWER: Abre una actividad para gestionar llamadas entrantes. ACTION_CALL: Inicia una llamada utilizando el número enviado en el URI. ACTION_DELETE: Borra una entrada de datos especificado en el URI. ACTION_DIAL: Aparece el marcador con el número especificado. ACTION_EDIT: Invoca una actividad para editar la información de el URI. ACTION_INSERT: Inserta nuevos items, por ejemplo contactos. ACTION_PICK: Recupera información de un item. ACTION_SEARCH: Invoca una actividad para realizar búsquedas. ACTION_SENDTO: Envía un mensaje a un contacto. ACTION_SEND: Envía información específica en el URI. ACTION_VIEW: Petición para ver información de la mejor manera posible. ACTION_WEB_SEARCH: Realiza búsquedas web de la info en el URI.
Broadcast Receiver Son componentes que responden a avisos y anuncios de difusión. Estos avisos pueden provenir de aplicaciones o del sistema como ser avisos de batería baja, una llamada entrante, etc. public class MyBroadcastReceiver extends BroadcastReceiver { @Override public void onreceive(context context, Intent intent) { //TODO: React to the Intent received. } }
Referencias http://startandroid.ru/en/lessons/complete-list/207-lesson-6-layouttypes-key-differences-and-properties.html http://developer.android.com/guide/practices/screens_support.html http://developer.android.com/guide/practices/screens_support.html #DeclaringTabletLayouts http://documents.cofares.net/miroires/androidpourvaleurc http://developer.android.com/reference/android/content/intent.html http://developer.android.com/guide/components/intents-filters.html
Próxima clase? - Servicios