Páginas

Entradas multilenguaje en blogger
Multilingual posts in blogger

Una de las grandes carencias de Blogger es el multilenguaje, ya que hasta la fecha no aporta una solución para poder publicar las entradas en diferentes idiomas.

Tras bastante tiempo probando soluciones encontradas por la web, he conseguido llegar a una opción bastante sencilla y satisfactoria, basada en jQuery. Su principal ventaja respecto a la mayoría de las que he visto, es que permite que la entrada y su título puedan verse en distintos idiomas, de forma que las visitas, comentarios, etc., son únicos. También intenta mostrar al visitante el idioma más adecuado, de acuerdo a la configuración del navegador.

La solución se basa en crear un panel con el contenido del texto en cada uno de los idiomas deseados, y añadir botones que muestran un idioma determinado, y ocultan el resto.

La solución, paso a paso, sería:

1. Añadir la librería jQuery a la plantilla de nuestro blog. Para ello, vamos a Plantilla - Editar HTML, y en el código búscamos la etiqueta </head>. Justo detrás copiamos la siguiente línea:

<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js' type='text/javascript'/>

2. Añadir el script que selecciona el idioma por defecto, y controla las pulsaciones de los botones. Lo pegamos detrás de la línea anterior:

<script type='text/javascript'>
   $(document).ready(function() {
   <!-- Select the initial language -->
   var userLang = navigator.language || navigator.userLanguage; 
   if (userLang.indexOf(&quot;es&quot;) &gt;= 0) {
  $(&quot;div.english&quot;).hide();
   }
   else {
  $(&quot;div.spanish&quot;).hide();
   }
  <!-- If spanish button is clicked, hide english text, and show spanish text -->
  $(&quot;#spanish_button&quot;).click(function () {
    $(&quot;div.english&quot;).hide();
    $(&quot;div.spanish&quot;).fadeIn(300);
  });
  
  <!-- If english button is clicked, hide spanish text, and show english text -->
  $(&quot;#english_button&quot;).click(function () {
    $(&quot;div.english&quot;).fadeIn(300);
    $(&quot;div.spanish&quot;).hide();
  });
   });
 </script>

3. Añadir los botones para cambiar de idioma. Podemos ponerlos en cada una de las entradas, pegando siempre el código al comienzo de las mismas, en la vista HTML, o en algún lugar fijo del blog. En mi caso los he colocado en la cabecera. Como fuente de las imágenes debéis poner la ruta a aquellas que queráis utilizar.

<img align='right' height='50' id='english_button' src=%your_image% width='50'/>
<img align='right' height='50' id='spanish_button' src=%your_image% width='50'/>

4. Para cada entrada, escribir el texto en cada uno de los idiomas, dentro de una etiqueta div, indicando el idioma en el atributo class:

<div class="english">
English Text.
</div>
<div class="espanish">
Spanish Text.
</div>

Y ya está. Podéis ver el resultado en este mismo blog. Puedes añadir tantos idiomas como quieras.
One of the major shortcomings of Blogger is multilingual and, to date, it does not provide a solution to publish entries in different languages.

After some time testing solutions found in the web, I got a fairly simple and satisfactory option, based on jQuery. Its main advantage over most I've seen, is that it allows one entry with different languages, so that the views, comments, etc., are unique. It also attempts to show visitors the most appropriate language, according to the browser settings.

The solution is to create a panel with the contents of the entry in each of the desired languages, and add buttons for each language, showing the corresponding panel when it´s pressed, and hidding the others.

The solution, step by step:

1. Add the jQuery library to our blog template. To do this, go to Template - Edit HTML, and in code we search for </head>. Just behind, copy the following line:

<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js' type='text/javascript'/>

2. Add the script to select default language, and control clicks on the buttons. Paste it below the import line.

<script type='text/javascript'>
   $(document).ready(function() {
   <!-- Select the initial language -->
   var userLang = navigator.language || navigator.userLanguage; 
   if (userLang.indexOf(&quot;es&quot;) &gt;= 0) {
  $(&quot;div.english&quot;).hide();
   }
   else {
  $(&quot;div.spanish&quot;).hide();
   }
  <!-- If spanish button is clicked, hide english text, and show spanish text -->
  $(&quot;#spanish_button&quot;).click(function () {
    $(&quot;div.english&quot;).hide();
    $(&quot;div.spanish&quot;).fadeIn(300);
  });
  
  <!-- If english button is clicked, hide spanish text, and show english text -->
  $(&quot;#english_button&quot;).click(function () {
    $(&quot;div.english&quot;).fadeIn(300);
    $(&quot;div.spanish&quot;).hide();
  });
   });
 </script>

3. Add buttons to change language. We can place them in each post; to do that, we have to paste the code in the beginning of each one. The other option is to place the buttons in a fixed location. (Change %your_image% by the url of the image you want to use for the button).

<img align='right' height='50' id='english_button' src=%your_image% width='50'/>
<img align='right' height='50' id='spanish_button' src=%your_image% width='50'/>

4. For each post, write the text for each language in a div tag, indicating the language in class attribute. Do the same for the title.

<div class="english">
English Text.
</div>
<div class="espanish">
Spanish Text.
</div>

And that's it. You can see the result in the entries of this blog. You can add as many languages ​​as you want.

Now, I just have to improve my english...

Texto alternativo para listas vacías
Alternative text for empty lists

La clase ListView de Android ofrece el método setEmptyView, que permite mostrar un mensaje al usuario si una lista está vacía. Para utilizarlo, es necesario definir en el layout de la página un elemento con visibilidad gone, que será el que se le pase a dicho método.

Como ejemplo podemos ver cómo se ha implementado la lista de jugadores de Memory Battle. Este es el fragmento del fichero de layout.

    <ListView
        android:id="@+id/players_list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" /> 

    <TextView
        android:id="@+id/no_players_text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/playersList"
        android:text="@string/no_players"
        android:visibility="gone" />

Y este el código que indica a la lista que debe usar el TextView como vista a mostrar cuando no tiene elementos.

playersList = (ListView) findViewById(R.id.playersList);
playersList.setEmptyView(findViewById(R.id.no_players_text));

Dado que lo que espera setEmptyView es un objeto View, se podría cambiar el texto por cualquier otro componente, como una imagen.
ListView class in Android provides setEmptyView method, which allows us to show a message to the user if the list is empty. To use it, we have to define in the layout file an element with gone visibility. That will be the parameter for setEmptyView.

This example shows how I´ve implemented the players list on Memory Battle. This is the fragment in the layout file:

    <ListView
        android:id="@+id/players_list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" /> 

    <TextView
        android:id="@+id/no_players_text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/playersList"
        android:text="@string/no_players"
        android:visibility="gone" />

And this is the code to tell the list that it has to show the TextView when it has no elements.

playersList = (ListView) findViewById(R.id.playersList);
playersList.setEmptyView(findViewById(R.id.no_players_text));

You can use any View object as parameter for setEmptyView, so you could change the text for an image, for example.

Cadenas con parámetros
Parameters in strings

Cuando obtenemos cadenas de texto del fichero string.xml, tenemos una serie de opciones avanzadas, que incluyen la utilización de parámetros.

Un ejemplo clásico es aquél en que la cadena va a mostrar un dato de negocio, como podría ser el nombre del usuario. Puede que alguna vez hayas solucionado este problema sencillamente concatenando la cadena obtenida del fichero xml, con el nombre:

getString(R.string.hello) + Model.user_name;

Esta solución es perfectamente válida, pero no nos valdría si queremos insertar el valor en medio de la cadena. En este caso podemos aprovechar la posibilidad de añadir parámetros. En el fichero string.xml tendríamos una entrada como esta.


<string name="hello">Hola %1$s, bienvenido</string>

Cada parámetro contiene un dígito que sirve como identificador secuencial, y otro que indica su tipo: s - string, d - decimal...

En código podemos completar la cadena con la siguiente línea.

String.format(getString(R.string.hello), Model.user_name);

El método format de la clase String admite tantos parámetros como sean necesarios, por lo que podemos añadir tantos como queramos en la definición del texto.
When we get string from string.xml file, we can use some advanzed options, including using parameters.

For example, if we want to show a business data, like username. A simple solution is to concatenate it with a string from xml file:

getString(R.string.hello) + Model.user_name;

This is a correct solution, but not enough if we want to insert the value in the middle of the chain. In this case we can use the possibility to add parameters. We need an entry like this in the file string.xml.


<string name="hello">Hello %1$s, wellcome</string>

Each parameter has one digit that is used as a sequential identifier, and another one to tell the type: s - string, d - decimal...

In our code, we can complete the string with the next line.

String.format(getString(R.string.hello), Model.user_name);

Format method on class String can receive as many parameters as needed, so we can add all we need.