Páginas

Asignar id a una vista en ejecución
Assign id to a view programmatically

Cuando se declara una vista en un fichero layout de Android, lo habitual es asignarle automáticamente un id.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/boardLayout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

Sin embargo, puede haber casos en que no podamos hacerlo. Por ejemplo, si queremos reutilizar una vista por medio de la etiqueta include, y necesitamos que cada instancia de la vista tenga un identificador distinto.

En estos casos tenemos la posibilidad de definir identificadores en un fichero de recursos.

<resources>
    <item name="id_1" type="id"/>
</resoruces>

Estos identificadores serán creados en la clase R, por lo que podremos recuperarlos y asignarlos a una vista con el siguiente código.

String name = "id" + i;   
view.setId(getResources().getIdentifier(name, "id", getPackageName()));

A partir de ese momento podremos recuperar la vista buscando por el id.
Views are usually declared in Android layout files with and id.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/boardLayout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

However, sometimes we can´t assign the id. For example, if we want to reuse a view with include tag, and we need each instance to have a different id.

In this situation, we have the option to define ids in a resource file.

<resources>
    <item name="id_1" type="id"/>
</resoruces>

This identifiers are created in R class, so you can access and assign them to a view in code.

String name = "id" + i;   
view.setId(getResources().getIdentifier(name, "id", getPackageName()));

From this point, we can find the view searching by id.

Evitar el giro de pantalla en Android
Avoid screen rotation in Android

Por defecto, las actividades Android se adaptan automáticamente a la orientación del dispositivo. Si queremos evitar este comportamiento no tenemos más que definir en el fichero AndroidManifest.xml de nuestra aplicación cuál es la orientación que debe tener cada actividad (portrait para vertical, y landscape para horizontal).

<activity android:name="package.YourActivity"
          android:screenOrientation="portrait" >

By default, Android activities adapt to device orientation. If we want to avoid this behaviour, we just have to define and orientation for any activity on AndroidManifest.xml file (portrait or landscape).

<activity android:name="package.YourActivity"
          android:screenOrientation="portrait" >

Evitar que se apague la pantalla
Keep the screen on

Cuando se está programando un juego, podemos requerir que la pantalla del dispositivo permanezca encendida incluso si el usuario pasa un tiempo sin interactuar. Es habitual encontrar soluciones que proponen el uso de wake locks, pero estos tienen dos grandes inconvenientes: requieren permisos especiales, y hacen que el programador tenga que ocuparse de liberarlos en el momento oportuno.

Existe una solución mucho más simple, que de hecho es recomendada en la página de desarrolladores de Android: usar el flag keep_screen_on. Este flag puede activarse para actividades individuales, tanto desde el manifest de la aplicación, como desde código. Esta segunda opción tiene la ventaja de que el flag puede igualmente desactivarse por código si en algún momento ya no es necesario.

En el manifest, declararíamos una actividad así:

<activity android:name="jvel.android.games.saveme.MainActivity" 
          android:keepScreenOn="true" />

En código, añadiríamos las siguientes líneas:

protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}

Si optamos por la opción de código, y más adelante queremos eliminar el flag:

getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)

When we are programming a game, we may want the screen of the device to keep on. There´s a solution based on wake locks, but it has two big advantages: it requieres special permission, and the developer needs to worry about releasing unused locks.

There is a much simpler solution, that is recommended in Android developers page: using flag_keep_screen_on. This flag can be activated only in an activity, from manifest or from code. This scond option has the adventage that the flag can be cleared if you don´t need it, allowing the screen to turn off again.

In manifest, we can declare an activity with:

<activity android:name="jvel.android.games.saveme.MainActivity" 
          android:keepScreenOn="true" />

In code, we have to add this line:

protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}

If we choose code option, and we want to clear the flag:

getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)

Añadir scroll a una actividad
Making an activity scrollable

Una duda habitual cuando se empieza a trabajar con Android es cómo añadir scroll a una actividad, o a algún componente de la interfaz. Y la verdad es que la solución es muy simple. Basta con añadir un ScrollView por encima del elemento al que queramos añadir el scroll.

Es importante tener en cuenta que la etiqueta ScrollView admite un único hijo. Lo habitual es que ese hijo sea un layout que a su vez contenga los elementos sobre los que se quiere hacer scroll.

Por tanto, si queremos que se pueda hacer scroll sobre la pantalla completa de una actividad, tendríamos algo así:

<ScrollView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >
        <!-- your components -->
    </RelativeLayout>
</ScrollView>

Si queremos aplicar el scroll a un grupo concreto de componentes de nuestra actividad, también podemos hacerlo. Por ejemplo, esta es la estructura de la actividad de configuración del juego en Batalla de Memoria, que deja la publicidad fija en la parte superior, y el botón en la inferior, haciendo que la barra de desplazamiento sólo afecte a las opciones en sí.

<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">

    <LinearLayout
        android:id="@+id/adLayout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:orientation="horizontal" >
    </LinearLayout>

    <ScrollView
        android:id="@+id/options_layout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/adLayout"
        android:layout_above="@+id/playButton" >
        
        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" >
            <!-- your components -->
        </RelativeLayout>
    </ScrollView>

    <Button
        android:id="@+id/playButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
         />

</RelativeLayout>
A typical question when someone is beginning with Android is how to add scroll to an activity, or a component of the interface. It has a really simple solution. You just have to add a ScrollView tag above the element you want to scroll.

It´s important to note that ScrollView tag supports just one child. It uses to be a layout that contains the rest of the components.

Therefore, if we want to make scroll over the entire interface of an activity, we have to write something like this:

<ScrollView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >
        <!-- your components -->
    </RelativeLayout>
</ScrollView>

If we want to apply scroll to a concrete group of components, we also can do it. This is the structure of configuration activity in Match Pairs Battle, which lets ad at the top, a button at the bottom, and allows scroll over the options.

<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">

    <LinearLayout
        android:id="@+id/adLayout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:orientation="horizontal" >
    </LinearLayout>

    <ScrollView
        android:id="@+id/options_layout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/adLayout"
        android:layout_above="@+id/playButton" >
        
        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" >
            <!-- your components -->
        </RelativeLayout>
    </ScrollView>

    <Button
        android:id="@+id/playButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
         />

</RelativeLayout>