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.

No hay comentarios:

Publicar un comentario