Android Training/Building a Simple User Interface: Unterschied zwischen den Versionen

Aus Android Wiki
Keine Bearbeitungszusammenfassung
 
(17 dazwischenliegende Versionen desselben Benutzers werden nicht angezeigt)
Zeile 1: Zeile 1:
[[Datei:Viewgroup.png|thumb|Illustration of how ViewGroup objects form branches in the layout and contain View objects.]]
<languages/>
The graphical user interface for an Android app is built using a hierarchy of View and ViewGroup objects. View objects are usually UI widgets such as a button or text field and ViewGroup objects are invisible view containers that define how the child views are laid out, such as in a grid or a vertical list.
[[Datei:Viewgroup.png|thumb|<translate><!--T:37-->
Illustration of how ViewGroup objects form branches in the layout and contain View objects.</translate>]]
<translate><!--T:1-->
In this lesson, you create a layout in XML that includes a text field and a button. In the next lesson, your app responds when the button is pressed by sending the content of the text field to another activity.


Android provides an XML vocabulary that corresponds to the subclasses of View and ViewGroup so you can define your UI in XML with a hierarchy of view elements.
<!--T:2-->
The graphical user interface for an Android app is built using a hierarchy of <code>View</code> and <code>ViewGroup</code> objects. <code>View</code> objects are usually UI widgets such as buttons or text fields. <code>ViewGroup</code> objects are invisible view containers that define how the child views are laid out, such as in a grid or a vertical list.


In this lesson, you'll create a layout in XML that includes a text input field and a button. In the following lesson, you'll respond when the button is pressed by sending the content of the text field to another activity.
<!--T:3-->
Android provides an XML vocabulary that corresponds to the subclasses of <code>View</code> and <code>ViewGroup</code> so you can define your UI in XML using a hierarchy of UI elements.


== Use Linear Layout ==
<!--T:4-->
Open the main.xml file from the res/layout/ directory (every new Android project includes this file by default).
<code>Layouts</code> are subclasses of the <code>ViewGroup</code>. In this exercise, you'll work with a <code>LinearLayout</code>.


Note: In Eclipse, when you open a layout file, you’re first shown the ADT Layout Editor. This is an editor that helps you build layouts using WYSIWYG tools. For this lesson, you’re going to work directly with the XML, so click the main.xml tab at the bottom of the screen to open the XML editor.
== Create a Linear Layout == <!--T:5-->
# In Android Studio, from the <code>res/layout</code> directory, open the <code>activity_my.xml</code> file.
#: The BlankActivity template you chose when you created this project includes the <code>activity_my.xml</code> file with a RelativeLayout root view and a <code>TextView</code> child view.
# In the Preview pane, click the Hide icon  to close the Preview pane.
# In Android Studio, when you open a layout file, you’re first shown the Preview pane. Clicking elements in this pane opens the WYSIWYG tools in the Design pane. For this lesson, you’re going to work directly with the XML.
# Delete the [http://developer.android.com/reference/android/widget/TextView.html <code><TextView></code>] element.
# Change the [http://developer.android.com/reference/android/widget/RelativeLayout.html <code><RelativeLayout></code>] element to [http://developer.android.com/reference/android/widget/LinearLayout.html <code><LinearLayout></code>].
# Add the [http://developer.android.com/reference/android/widget/LinearLayout.html#attr_android:orientation <code>android:orientation</code>] attribute and set it to <code>"horizontal"</code>.
# Remove the <code>android:padding</code> attributes and the <code>tools:context</code> attribute.


By default, the main.xml file includes a layout with a LinearLayout root view group and a TextView child view. You’re going to re-use the LinearLayout in this lesson, but change its contents and layout orientation.
<!--T:6-->
 
The result looks like this:
First, delete the TextView element and change the value android:orientation to be "horizontal". The result looks like this:
</translate>
<source lang="xml">
''res/layout/activity_my.xml''
<?xml version="1.0" encoding="utf-8"?>
<syntaxhighlight lang="xml">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="fill_parent"
    xmlns:tools="http://schemas.android.com/tools"
     android:layout_height="fill_parent"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:orientation="horizontal" >
     android:orientation="horizontal" >
</LinearLayout>
</LinearLayout>
</source>
</syntaxhighlight>
<translate>
<!--T:7-->
<code>LinearLayout</code> is a view group (a subclass of [http://developer.android.com/reference/android/view/ViewGroup.html <code>ViewGroup</code>]) that lays out child views in either a vertical or horizontal orientation, as specified by the <code>android:orientation</code> attribute. Each child of a LinearLayout appears on the screen in the order in which it appears in the XML.


[http://developer.android.com/reference/android/widget/LinearLayout.html LinearLayout] is a [http://developer.android.com/reference/android/view/ViewGroup.html view group] (a subclass of ViewGroup) that lays out child views in either a vertical or horizontal orientation, as specified by the [http://developer.android.com/reference/android/widget/LinearLayout.html#attr_android:orientation android:orientation] attribute. Each child of a LinearLayout appears on the screen in the order in which it appears in the XML.
<!--T:8-->
Two other attributes, <code>android:layout_width</code> and <code>android:layout_height</code>, are required for all views in order to specify their size.


The other two attributes, [http://developer.android.com/reference/android/view/View.html#attr_android:layout_width android:layout_width] and [http://developer.android.com/reference/android/view/View.html#attr_android:layout_height android:layout_height], are required for all views in order to specify their size.
<!--T:9-->
Because the <code>LinearLayout</code> is the root view in the layout, it should fill the entire screen area that's available to the app by setting the width and height to <code>"match_parent"</code>. This value declares that the view should expand its width or height to match the width or height of the parent view.


Because the LinearLayout is the root view in the layout, it should fill the entire screen area that's available to the app by setting the width and height to "fill_parent".
<!--T:10-->
For more information about layout properties, see the Layout guide.


Note: Beginning with Android 2.2 (API level 8), "fill_parent" has been renamed "match_parent" to better reflect the behavior. The reason is that if you set a view to "fill_parent" it does not expand to fill the remaining space after sibling views are considered, but instead expands to match the size of the parent view no matter what—it will overlap any sibling views.
== Add a Text Field == <!--T:11-->
As with every [http://developer.android.com/reference/android/view/View.html <code>View</code>] object, you must define certain XML attributes to specify the [http://developer.android.com/reference/android/widget/EditText.html <code>EditText</code>] object's properties.


For more information about layout properties, see the [http://developer.android.com/guide/topics/ui/declaring-layout.html XML Layout] guide.
<!--T:12-->
# In the <code>activity_my.xml</code> file, within the <code><LinearLayout></code> element, define an <code><EditText></code> element with the id attribute set to @+id/edit_message.
# Define the <code>layout_width</code> and <code>layout_height</code> attributes as <code>wrap_content</code>.
# Define a <code>hint</code> attribute as a string object named <code>edit_message</code>.


== Add a text field ==
<!--T:13-->
To create a user-editable text field, add an [http://developer.android.com/reference/android/widget/EditText.html <EditText>] element inside the <LinearLayout>. The EditText class is a subclass of [http://developer.android.com/reference/android/view/View.html View] that displays an editable text field.
The <code><EditText></code> element should read as follows:
</translate>
''res/layout/activity_my.xml''
<syntaxhighlight lang="xml">
<EditText android:id="@+id/edit_message"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:hint="@string/edit_message" />
</syntaxhighlight>
<translate>
<!--T:14-->
Here are the <EditText> attributes you added:


Like every View object, you must define certain XML attributes to specify the EditText object's properties. Here’s how you should declare it inside the <LinearLayout> element:
=== [http://developer.android.com/reference/android/view/View.html#attr_android:id <code>android:id</code>] === <!--T:15-->
<source lang="xml">
This provides a unique identifier for the view, which you can use to reference the object from your app code, such as to read and manipulate the object (you'll see this in the next lesson).
<EditText android:id="@+id/edit_message"
The at sign (<code>@</code>) is required when you're referring to any resource object from XML. It is followed by the resource type (<code>id</code> in this case), a slash, then the resource name (<code>edit_message</code>).
        android:layout_width="wrap_content"
The plus sign (<code>+</code>) before the resource type is needed only when you're defining a resource ID for the first time. When you compile the app, the SDK tools use the ID name to create a new resource ID in your project's <code>gen/R.java</code> file that refers to the EditText element. With the resource ID declared once this way, other references to the ID do not need the plus sign. Using the plus sign is necessary only when specifying a new resource ID and not needed for concrete resources such as strings or layouts. See the sidebox for more information about resource objects.
        android:layout_height="wrap_content"
        android:hint="@string/edit_message" />
</source>
About these attributes:


#; <nowiki>android:id</nowiki> : This provides a unique identifier for the view, which you can use to reference the object from your app code, such as to read and manipulate the object (you'll see this in the next lesson).
=== [http://developer.android.com/reference/android/view/View.html#attr_android:layout_width <code>android:layout_width</code>] and [http://developer.android.com/reference/android/view/View.html#attr_android:layout_height <code>android:layout_height</code>] === <!--T:16-->
The at-symbol (@) is required when you want to refer to a resource object from XML, followed by the resource type (id in this case), then the resource name (edit_message). (Other resources can use the same name as long as they are not the same resource type—for example, the string resource uses the same name.)
Instead of using specific sizes for the width and height, the <code>"wrap_content"</code> value specifies that the view should be only as big as needed to fit the contents of the view. If you were to instead use <code>"match_parent"</code>, then the <code>EditText</code> element would fill the screen, because it would match the size of the parent <code>LinearLayout</code>. For more information, see the Layouts guide.
The plus-symbol (+) is needed only when you're defining a resource ID for the first time. It tells the SDK tools that the resource ID needs to be created. Thus, when the app is compiled, the SDK tools use the ID value, edit_message, to create a new identifier in your project's gen/R.java file that is now associated with the EditText element. Once the resource ID is created, other references to the ID do not need the plus symbol. This is the only attribute that may need the plus-symbol. See the sidebox for more information about resource objects.
#; <nowiki>android:layout_width and android:layout_height</nowiki>
Instead of using specific sizes for the width and height, the "wrap_content" value specifies that the view should be only as big as needed to fit the contents of the view. If you were to instead use "fill_parent", then the EditText element would fill the screen, because it'd match the size of the parent LinearLayout. For more information, see the XML Layouts guide.
#; <nowiki>android:hint</nowiki>
This is a default string to display when the text field is empty. Instead of using a hard-coded string as the value, the "@string/edit_message" value refers to a string resource defined in a separate file. Because this value refers to an existing resource, it does not need the plus-symbol. However, because you haven't defined the string resource yet, you’ll see a compiler error when you add the "@string/edit_message" value. You'll fix this in the next section by defining the string resource.


== Add String Resources ==
=== [http://developer.android.com/reference/android/widget/TextView.html#attr_android:hint <code>android:hint</code>] === <!--T:17-->
This is a default string to display when the text field is empty. Instead of using a hard-coded string as the value, the <code>"@string/edit_message"</code> value refers to a string resource defined in a separate file. Because this refers to a concrete resource (not just an identifier), it does not need the plus sign. However, because you haven't defined the string resource yet, you’ll see a compiler error at first. You'll fix this in the next section by defining the string.


When you need to add text in the user interface, you should always specify each string of text in a resource file. String resources allow you to maintain a single location for all string values, which makes it easier to find and update text. Externalizing the strings also allows you to localize your app to different languages by providing alternative definitions for each string.
== Add String Resources == <!--T:18-->
By default, your Android project includes a string resource file at <code>res/values/strings.xml</code>. Here, you'll add a new string named <code>"edit_message"</code> and set the value to "Enter a message."


By default, your Android project includes a string resource file at res/values/strings.xml. Open this file, delete the existing "hello" string, and add one for the "edit_message" string used by the <EditText> element.
<!--T:19-->
# In [[Android Studio]], from the <code>res/values</code> directory, open <code>strings.xml</code>.
# Add a line for a string named <code>"edit_message"</code> with the value, "Enter a message".
# Add a line for a string named <code>"button_send"</code> with the value, "Send".
# You'll create the button that uses this string in the next section.
# Remove the line for the <code>"hello world"</code> string.


While you’re in this file, also add a string for the button you’ll soon add, called "button_send".
<!--T:20-->
The result for <code>strings.xml</code> looks like this:


The result for strings.xml looks like this:
</translate>
<source lang="xml">
''res/values/strings.xml''
<syntaxhighlight lang="xml">
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<resources>
Zeile 68: Zeile 103:
     <string name="edit_message">Enter a message</string>
     <string name="edit_message">Enter a message</string>
     <string name="button_send">Send</string>
     <string name="button_send">Send</string>
    <string name="action_settings">Settings</string>
    <string name="title_activity_main">MainActivity</string>
</resources>
</resources>
</source>
</syntaxhighlight>
For more information about using string resources to localize your app for several languages, see the [http://developer.android.com/training/basics/supporting-devices/index.html Supporting Various Devices] class.
<translate>
<!--T:21-->
For text in the user interface, always specify each string as a resource. String resources allow you to manage all UI text in a single location, which makes the text easier to find and update. Externalizing the strings also allows you to localize your app to different languages by providing alternative definitions for each string resource.
 
<!--T:22-->
For more information about using string resources to localize your app for other languages, see the Supporting Different Devices class.
 
== Add a Button == <!--T:23-->
# In Android Studio, from the <code>res/layout</code> directory, edit the <code>activity_my.xml</code> file.
# Within the <code><LinearLayout></code> element, define a [http://developer.android.com/reference/android/widget/Button.html <code><Button></code>] element immediately following the <code><EditText></code> element.
# Set the button's width and height attributes to <code>"wrap_content"</code> so the button is only as big as necessary to fit the button's text label.
# Define the button's text label with the [http://developer.android.com/reference/android/widget/TextView.html#attr_android:text <code>android:text</code>] attribute; set its value to the <code>button_send</code> string resource you defined in the previous section.
Your <code><LinearLayout></code> should look like this:


== Add a Button ==
</translate>
Now add a [http://developer.android.com/reference/android/widget/Button.html <Button>] to the layout, immediately following the [http://developer.android.com/reference/android/widget/EditText.html <EditText>] element:
''res/layout/activity_my.xml''
<source lang="xml">
<syntaxhighlight lang="xml">
<Button
<LinearLayout 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"
    android:orientation="horizontal" >
      <EditText android:id="@+id/edit_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="@string/edit_message" />
      <Button
         android:layout_width="wrap_content"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_height="wrap_content"
         android:text="@string/button_send" />
         android:text="@string/button_send" />
</source>
</LinearLayout>
The height and width are set to "wrap_content" so the button is only as big as necessary to fit the button's text. This button doesn't need the android:id attribute, because it won't be referenced from the activity code.
</syntaxhighlight>
<translate>
<!--T:24-->
'''Note''': This button doesn't need the <code>android:id</code> attribute, because it won't be referenced from the activity code.
</translate>
[[Datei:edittext_wrap.png|thumb|<translate><!--T:25-->
The EditText and Button widgets have their widths set to "wrap_content".</translate>]]
<translate>
<!--T:26-->
The layout is currently designed so that both the <code>EditText</code> and <code>Button</code> widgets are only as big as necessary to fit their content, as shown in the picture.
 
<!--T:27-->
This works fine for the button, but not as well for the text field, because the user might type something longer. It would be nice to fill the unused screen width with the text field. You can do this inside a <code>LinearLayout</code> with the weight property, which you can specify using the [http://developer.android.com/reference/android/widget/LinearLayout.LayoutParams.html#weight <code>android:layout_weight</code>] attribute.


== Make the Input Box Fill in the Screen Width ==
<!--T:28-->
The layout is currently designed so that both the EditText and Button widgets are only as big as necessary to fit their content, as shown in figure 2.
The weight value is a number that specifies the amount of remaining space each view should consume, relative to the amount consumed by sibling views. This works kind of like the amount of ingredients in a drink recipe: "2 parts soda, 1 part syrup" means two-thirds of the drink is soda. For example, if you give one view a weight of 2 and another one a weight of 1, the sum is 3, so the first view fills 2/3 of the remaining space and the second view fills the rest. If you add a third view and give it a weight of 1, then the first view (with weight of 2) now gets 1/2 the remaining space, while the remaining two each get 1/4.
[[Datei:edittext_wrap.png|thumb|The EditText and Button widgets have their widths set to "wrap_content".]]
This works fine for the button, but not as well for the text field, because the user might type something longer and there's extra space left on the screen. So, it'd be nice to fill that width using the text field. LinearLayout enables such a design with the weight property, which you can specify using the android:layout_weight attribute.


The weight value allows you to specify the amount of remaining space each view should consume, relative to the amount consumed by sibling views, just like the ingredients in a drink recipe: "2 parts vodka, 1 part coffee liqueur" means two-thirds of the drink is vodka. For example, if you give one view a weight of 2 and another one a weight of 1, the sum is 3, so the first view gets 2/3 of the remaining space and the second view gets the rest. If you give a third view a weight of 1, then the first view now gets 1/2 the remaining space, while the remaining two each get 1/4.
<!--T:29-->
The default weight for all views is 0, so if you specify any weight value greater than 0 to only one view, then that view fills whatever space remains after all views are given the space they require.


The default weight for all views is 0, so if you specify any weight value greater than 0 to only one view, then that view fills whatever space remains after each view is given the space it requires. So, to fill the remaining space with the EditText element, give it a weight of 1 and leave the button with no weight.
== Make the Input Box Fill in the Screen Width == <!--T:30-->
<source lang="xml">
To fill the remaining space in your layout with the <code>EditText</code> element, do the following:
 
<!--T:31-->
# In the <code>activity_my.xml</code> file, assign the <code><EditText></code> element's <code>layout_weight</code> attribute a value of <code>1</code>.
# Also, assign <code><EditText></code> element's <code>layout_width</code> attribute a value of <code>0dp</code>.
</translate>
#: ''res/layout/activity_my.xml''
#: <syntaxhighlight lang="xml">
<EditText
<EditText
        android:layout_weight="1"
    android:layout_weight="1"
        ... />
    android:layout_width="0dp"
</source>
    ... />
In order to improve the layout efficiency when you specify the weight, you should change the width of the EditText to be zero (0dp). Setting the width to zero improves layout performance because using "wrap_content" as the width requires the system to calculate a width that is ultimately irrelevant because the weight value requires another width calculation to fill the remaining space.
</syntaxhighlight>
<source lang="xml">
<translate>
<EditText
<!--T:32-->
        android:layout_weight="1"
To improve the layout efficiency when you specify the weight, you should change the width of the <code>EditText</code> to be zero (0dp). Setting the width to zero improves layout performance because using <code>"wrap_content"</code> as the width requires the system to calculate a width that is ultimately irrelevant because the weight value requires another width calculation to fill the remaining space.
        android:layout_width="0dp"
 
        ... />
<!--T:33-->
</source>
Here’s how your complete <code>activity_my.xml</code> layout file should now look:
Figure 3 shows the result when you assign all weight to the EditText element. <-----------selbe Bild wie figure 2 ;)
</translate>
Here’s how your complete layout file should now look:
''res/layout/activity_my.xml''
<source lang="xml">
<syntaxhighlight lang="xml">
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="fill_parent"
    xmlns:tools="http://schemas.android.com/tools"
     android:layout_height="fill_parent"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:orientation="horizontal">
     android:orientation="horizontal">
     <EditText android:id="@+id/edit_message"
     <EditText android:id="@+id/edit_message"
Zeile 120: Zeile 197:
         android:text="@string/button_send" />
         android:text="@string/button_send" />
</LinearLayout>
</LinearLayout>
</source>
</syntaxhighlight>
This layout is applied by the default Activity class that the SDK tools generated when you created the project, so you can now run the app (in lektion "[[Android Training/ Deine App starten|Android Training/ Deine app starten]]") to see the results.
<translate>
 
== Run Your App == <!--T:34-->
This layout is applied by the default <code>Activity</code> class that the SDK tools generated when you created the project. Run the app to see the results:
 
<!--T:35-->
# In Android Studio, from the toolbar, click '''Run'''.
# Or from a command line, change directories to the root of your Android project and execute:</translate>
#: <code>ant debug</code>
#: <code>adb install bin/MyFirstApp-debug.apk</code>
<translate>
<!--T:36-->
Continue to the next lesson to learn how to respond to button presses, read content from the text field, start another activity, and more.
</translate>


{{Android Training/ Vorlage:Attribution}}
{{TNT|Android Training/Attribution}}

Aktuelle Version vom 18. Dezember 2015, 18:23 Uhr

Sprachen:
Illustration of how ViewGroup objects form branches in the layout and contain View objects.

In this lesson, you create a layout in XML that includes a text field and a button. In the next lesson, your app responds when the button is pressed by sending the content of the text field to another activity.

The graphical user interface for an Android app is built using a hierarchy of View and ViewGroup objects. View objects are usually UI widgets such as buttons or text fields. ViewGroup objects are invisible view containers that define how the child views are laid out, such as in a grid or a vertical list.

Android provides an XML vocabulary that corresponds to the subclasses of View and ViewGroup so you can define your UI in XML using a hierarchy of UI elements.

Layouts are subclasses of the ViewGroup. In this exercise, you'll work with a LinearLayout.

Create a Linear Layout[Bearbeiten | Quelltext bearbeiten]

  1. In Android Studio, from the res/layout directory, open the activity_my.xml file.
    The BlankActivity template you chose when you created this project includes the activity_my.xml file with a RelativeLayout root view and a TextView child view.
  2. In the Preview pane, click the Hide icon to close the Preview pane.
  3. In Android Studio, when you open a layout file, you’re first shown the Preview pane. Clicking elements in this pane opens the WYSIWYG tools in the Design pane. For this lesson, you’re going to work directly with the XML.
  4. Delete the <TextView> element.
  5. Change the <RelativeLayout> element to <LinearLayout>.
  6. Add the android:orientation attribute and set it to "horizontal".
  7. Remove the android:padding attributes and the tools:context attribute.

The result looks like this: res/layout/activity_my.xml

<LinearLayout 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"
    android:orientation="horizontal" >
</LinearLayout>

LinearLayout is a view group (a subclass of ViewGroup) that lays out child views in either a vertical or horizontal orientation, as specified by the android:orientation attribute. Each child of a LinearLayout appears on the screen in the order in which it appears in the XML.

Two other attributes, android:layout_width and android:layout_height, are required for all views in order to specify their size.

Because the LinearLayout is the root view in the layout, it should fill the entire screen area that's available to the app by setting the width and height to "match_parent". This value declares that the view should expand its width or height to match the width or height of the parent view.

For more information about layout properties, see the Layout guide.

Add a Text Field[Bearbeiten | Quelltext bearbeiten]

As with every View object, you must define certain XML attributes to specify the EditText object's properties.

  1. In the activity_my.xml file, within the <LinearLayout> element, define an <EditText> element with the id attribute set to @+id/edit_message.
  2. Define the layout_width and layout_height attributes as wrap_content.
  3. Define a hint attribute as a string object named edit_message.

The <EditText> element should read as follows: res/layout/activity_my.xml

<EditText android:id="@+id/edit_message"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:hint="@string/edit_message" />

Here are the <EditText> attributes you added:

android:id[Bearbeiten | Quelltext bearbeiten]

This provides a unique identifier for the view, which you can use to reference the object from your app code, such as to read and manipulate the object (you'll see this in the next lesson). The at sign (@) is required when you're referring to any resource object from XML. It is followed by the resource type (id in this case), a slash, then the resource name (edit_message). The plus sign (+) before the resource type is needed only when you're defining a resource ID for the first time. When you compile the app, the SDK tools use the ID name to create a new resource ID in your project's gen/R.java file that refers to the EditText element. With the resource ID declared once this way, other references to the ID do not need the plus sign. Using the plus sign is necessary only when specifying a new resource ID and not needed for concrete resources such as strings or layouts. See the sidebox for more information about resource objects.

android:layout_width and android:layout_height[Bearbeiten | Quelltext bearbeiten]

Instead of using specific sizes for the width and height, the "wrap_content" value specifies that the view should be only as big as needed to fit the contents of the view. If you were to instead use "match_parent", then the EditText element would fill the screen, because it would match the size of the parent LinearLayout. For more information, see the Layouts guide.

android:hint[Bearbeiten | Quelltext bearbeiten]

This is a default string to display when the text field is empty. Instead of using a hard-coded string as the value, the "@string/edit_message" value refers to a string resource defined in a separate file. Because this refers to a concrete resource (not just an identifier), it does not need the plus sign. However, because you haven't defined the string resource yet, you’ll see a compiler error at first. You'll fix this in the next section by defining the string.

Add String Resources[Bearbeiten | Quelltext bearbeiten]

By default, your Android project includes a string resource file at res/values/strings.xml. Here, you'll add a new string named "edit_message" and set the value to "Enter a message."

  1. In Android Studio, from the res/values directory, open strings.xml.
  2. Add a line for a string named "edit_message" with the value, "Enter a message".
  3. Add a line for a string named "button_send" with the value, "Send".
  4. You'll create the button that uses this string in the next section.
  5. Remove the line for the "hello world" string.

The result for strings.xml looks like this:

res/values/strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">My First App</string>
    <string name="edit_message">Enter a message</string>
    <string name="button_send">Send</string>
    <string name="action_settings">Settings</string>
    <string name="title_activity_main">MainActivity</string>
</resources>

For text in the user interface, always specify each string as a resource. String resources allow you to manage all UI text in a single location, which makes the text easier to find and update. Externalizing the strings also allows you to localize your app to different languages by providing alternative definitions for each string resource.

For more information about using string resources to localize your app for other languages, see the Supporting Different Devices class.

Add a Button[Bearbeiten | Quelltext bearbeiten]

  1. In Android Studio, from the res/layout directory, edit the activity_my.xml file.
  2. Within the <LinearLayout> element, define a <Button> element immediately following the <EditText> element.
  3. Set the button's width and height attributes to "wrap_content" so the button is only as big as necessary to fit the button's text label.
  4. Define the button's text label with the android:text attribute; set its value to the button_send string resource you defined in the previous section.

Your <LinearLayout> should look like this:

res/layout/activity_my.xml

<LinearLayout 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"
    android:orientation="horizontal" >
      <EditText android:id="@+id/edit_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="@string/edit_message" />
      <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_send" />
</LinearLayout>

Note: This button doesn't need the android:id attribute, because it won't be referenced from the activity code.

The EditText and Button widgets have their widths set to "wrap_content".

The layout is currently designed so that both the EditText and Button widgets are only as big as necessary to fit their content, as shown in the picture.

This works fine for the button, but not as well for the text field, because the user might type something longer. It would be nice to fill the unused screen width with the text field. You can do this inside a LinearLayout with the weight property, which you can specify using the android:layout_weight attribute.

The weight value is a number that specifies the amount of remaining space each view should consume, relative to the amount consumed by sibling views. This works kind of like the amount of ingredients in a drink recipe: "2 parts soda, 1 part syrup" means two-thirds of the drink is soda. For example, if you give one view a weight of 2 and another one a weight of 1, the sum is 3, so the first view fills 2/3 of the remaining space and the second view fills the rest. If you add a third view and give it a weight of 1, then the first view (with weight of 2) now gets 1/2 the remaining space, while the remaining two each get 1/4.

The default weight for all views is 0, so if you specify any weight value greater than 0 to only one view, then that view fills whatever space remains after all views are given the space they require.

Make the Input Box Fill in the Screen Width[Bearbeiten | Quelltext bearbeiten]

To fill the remaining space in your layout with the EditText element, do the following:

  1. In the activity_my.xml file, assign the <EditText> element's layout_weight attribute a value of 1.
  2. Also, assign <EditText> element's layout_width attribute a value of 0dp.
    res/layout/activity_my.xml
    <EditText
        android:layout_weight="1"
        android:layout_width="0dp"
        ... />
    

To improve the layout efficiency when you specify the weight, you should change the width of the EditText to be zero (0dp). Setting the width to zero improves layout performance because using "wrap_content" as the width requires the system to calculate a width that is ultimately irrelevant because the weight value requires another width calculation to fill the remaining space.

Here’s how your complete activity_my.xml layout file should now look: res/layout/activity_my.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="horizontal">
    <EditText android:id="@+id/edit_message"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="@string/edit_message" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_send" />
</LinearLayout>

Run Your App[Bearbeiten | Quelltext bearbeiten]

This layout is applied by the default Activity class that the SDK tools generated when you created the project. Run the app to see the results:

  1. In Android Studio, from the toolbar, click Run.
  2. Or from a command line, change directories to the root of your Android project and execute:
    ant debug
    adb install bin/MyFirstApp-debug.apk

Continue to the next lesson to learn how to respond to button presses, read content from the text field, start another activity, and more.