Dienstag, 22. Januar 2008

Android-GUI mit XML-Layoutdatei

Android ermöglicht es, grafische Benutzeroberflächen (GUIs) mit Hilfe von XML-Dateien zu designen. Diese Vorgehensweise ähnelt damit dem Design von Webseiten, z.B. mit HTML. Eine XML-Datei main.xml zur Layoutgestaltung befindet sich dabei im Unterverzeichnis res/layout/. Das Display des Emulators soll eine einfache Textausgabe, ein Eingabefeld und zwei Buttons anzeigen.

Die für das Layout zuständige Datei main.xml könnte dann wie folgt aussehen:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" 
android:layout_height="wrap_content"
android:background="#ffc5d1d4" 
android:padding="10px">

  <TextView id="@+id/label" 
            android:layout_width="fill_parent" 
            android:layout_height="wrap_content" 
            android:text="Your Input:"/>
  <EditText id="@+id/input" 
            android:layout_width="fill_parent" 
            android:layout_height="wrap_content" 
            android:layout_below="@id/label"/>
  <Button   id="@+id/ok" 
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content"
            android:layout_below="@id/input"
            android:layout_alignParentRight="true"
            android:layout_marginLeft="10px"
            android:text="OK"/>
  <Button   id="@+id/cancel"
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content"
            android:layout_toLeft="@id/ok"
            android:layout_alignTop="@id/ok"
            android:text="Cancel" />
</RelativeLayout>

Jetzt fehlt nur noch das kurze Java-Listing, das die Layout-Ressource lädt bzw. verarbeitet. Innerhalb der Methode onCreate ist hierzu der Aufruf von setContentView nötig. Die Applikation ist damit vollständig und kann aus Eclipse heraus gestartet werden.

/* RelativeLayoutExample.java */

package examples.android.relativelayoutexample;

import android.app.Activity;
import android.os.Bundle;

public class RelativeLayoutExample extends Activity {
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    
    setContentView(R.layout.main);
  } 
}

Keine Kommentare: