Tecnologías Móviles

clase 3

Intents

Es una forma de intercambiar mensajes entre elementos de la misma o diferentes aplicaciones.

 

Se utilizan principalmente para:

  • Iniciar un Activity
  • Iniciar un Service
  • Enviar un mensaje Broadcast

Intents

// Create the text message with a string
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, textMessage);
sendIntent.setType("text/plain");

// Verify that the intent will resolve to an activity
if (sendIntent.resolveActivity(getPackageManager()) != null) {
    startActivity(sendIntent);
}
// Executed in an Activity, so 'this' is the Context
// The fileUrl is a string URL, such as "http://www.example.com/image.png"
Intent downloadIntent = new Intent(this, DownloadService.class);
downloadIntent.setData(Uri.parse(fileUrl));
startService(downloadIntent);

Intent Explícito

Intent Impícito

Activity - Ciclo de Vida

public class ExampleActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // The activity is being created.
    }
    @Override
    protected void onStart() {
        super.onStart();
        // The activity is about to become visible.
    }
    @Override
    protected void onResume() {
        super.onResume();
        // The activity has become visible (it is now "resumed").
    }
    @Override
    protected void onPause() {
        super.onPause();
        // Another activity is taking focus (this activity is about to be "paused").
    }
    @Override
    protected void onStop() {
        super.onStop();
        // The activity is no longer visible (it is now "stopped")
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // The activity is about to be destroyed.
    }
}

Activity - Configuraciones de onCreate

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //Seteo el Layout
    setContentView(R.layout.main_activity);

    //Obtengo un elemento dentro del Layout
    EditText nombre = (EditText) findViewById(R.id.nombre);

    //Seteo un listener para un boton
    Button button = (Button) findViewById(R.id.button_id);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Hacer algo cuando se hace click en un boton
            Intent intent = new Intent(this, DetailActivity.class);
            intent.putExtra("key", "value");
            startActivity(intent);
        }
    });

    ListView lista = (ListView) findViewById(R.id.lista);
    lista.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick (AdapterView<?> parent, 
                                View view, int position, long id) {
            //Hacer algo cuando se hace click a un elemento de la lista
        }
    });
}

Activity

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //Seteo el Layout
    setContentView(R.layout.detail_activity);

    //Obtengo el intent con el cual fué llamado el activity
    Intent intent = getIntent();
    String key = intent.getStringExtra("key");
}

Obtener el intent con el que fue llamado.

Activity - startActivityForResult

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Intent i = new Intent(this, ResultActivity.class);
    i.putExtra("apellido", "Perez");
    startActivityForResult(i, OBTENER_USUARIOS);
}
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Intent callingIntent = getIntent();
    String filtroApellido = callingIntent.getStringExtra("apellido");

    //Obtener datos de los usuarios

    Intent resultIntent = new Intent();
    resultIntent.putExtra("usuarios", usuarios);

    setResult(Activity.RESULT_OK, resultIntent);
    finish();
}
@Override
protected void onActivityResult(int requestCode, 
        int resultCode, Intent data) {
    
    if (resultCode == Activity.RESULT_OK 
            && requestCode == OBTENER_USUARIOS) {
        // Hacer algo con los datos de usuarios
        String[] usuarios = 
            data.getStringArrayExtra("usuarios");
    }
}
T

1

2

3

Adapters

Adapter adapter = new UsersAdapter();

ListView usuarios = (ListView) findViewById(R.id.usuarios);

usuarios.setAdapter(adapter);

Configurar el adapter de una lista

Un adapter es una clase que actúa como puente entre un AdapterView y los datos.

Los datos son un array de elementos, y el adapter es el encargado de generar el view correspondiente a cada uno.

Adapters

public class UsuarioAdapter extends BaseAdapter {

    private Context mContext;  
    private ArrayList<Usuario> mList;

    public UsuarioAdapter() {
        
    }

    public void setList(ArrayList<Usuario> list) {
        mList = list;
        notifyDataSetChanged();
    }

    @Override  
    public int getCount() {  
        return mList.size();  
    }  
    
    @Override  
    public Object getItem(int pos) {  
        return mList.get(pos);  
    }

    ...

}

Adapters

public class UsuarioAdapter extends BaseAdapter {

    ...

    public void addItem(Usuario usr) {
        mList.add(usr);
        notifyDataSetChanged();
    }  

    @Override  
    public long getItemId(int position) {  
        return position;  
    }
  
    @Override  
    public View getView(int position, View convertView, ViewGroup parent) {
        Usuario usr = getItem(position);
        if(convertView==null) {
            LayoutInflater li = LayoutInflater.from(mContext);
            convertView = li.inflate(R.layout.list_item, null);
        }
        TextView nombre = (TextView) convertView.findViewById(R.id.nombre);
        nombre.setText(usr.nombre);
        TextView nombre = (TextView) convertView.findViewById(R.id.apellido);
        nombre.setText(usr.nombre);
        return convertView;
    }

}

Ejercicio

  • Crear una aplicación que contenga los siguientes elementos:
    • Un Activity (ActivityListado) con un ListView y un botón "+"
    • Un segundo Activity (ActivityForm) que despliegue un formulario con tres EditText:
      • ​Nombre
      • Apellido
      • Mail
    • ActivityForm debe tener 2 botones: Aceptar y Cancelar
    • Cuando hago click en el botón "+" de ActivityListado, se debe abrir ActivityForm.
    • Si hago click en el botón Aceptar en ActivityForm, debe retornar a ActivityListado y agregar un usuario al listado.
    • Si hago click en el botón Cancelar, debe retornar a ActivityListado y no agregar ningún usuario a la lista.
    • Cada item del listado debe mostrar en una primera línea el nombre y apellido, y en la línea inferior el mail en color gris y mas pequeño.

Tecnologías Móviles - Clase 3

By Agustin Moyano

Tecnologías Móviles - Clase 3

  • 665