Quantcast
Channel: Thiranjith's Blog » Android
Viewing all articles
Browse latest Browse all 10

Creating multi-line EditText in Android

$
0
0

This is a small guide demonstrating how we can use Android EditText controls to create multi line text inputs.

Approach #1
The simplest way to create a multi line text input is using the following xml snippet:

<EditText android:id="@+id/txtMultiLine" 
              android:layout_width="200dip" 
              android:layout_height="wrap_content" 
              android:text="Default text" />

This will create a EditText view that displays the default text as shown in Figure 1 (a). When you enter new lines, the EditText will grow vertically (Figure 1 (b)). This might not be desirable in actual applications, as your layout becomes too fluid; potentially pushing important information out of user’s view.

Figure 1: Default EditText behaviour

Approach #2
The logical fix to ensure EditText occupies a fixed area on-screen is to add android:lines attribute to our XML. This is an integer defining how many lines should be visible to the user. Unlike the original approach, the text will scroll up as the user enters more text (and new lines) as shown in Figure 2 and will not change the height of EditText View.

<!-- An EditText with height to display 3 lines of text -->
    <EditText android:id="@+id/txtMultiLine" 
              android:layout_width="200dip" 
              android:layout_height="wrap_content" 
              android:lines="3" 
              android:text="Default text" />

Figure 2: Fixed-height multi line EditText

Aligning Text
As you can see from Figure 2 (1), the original text is aligned “centre horizontally”. Android provides full control over how to align text using android:gravity xml attribute. The following xml snippet demonstrates how to align the text so it will always start from top right corner of EditText (see Figure 3).

<!-- Same as above, but using gravity attribute to 
         align the text -->
    <EditText android:id="@+id/txtMultiLine" 
              android:layout_width="200dip" 
              android:layout_height="wrap_content" 
              android:lines="3" android:gravity="right|top" 
              android:text="Default text" />

android:gravity can be used whenever you use EditText (regardless whether it is single-line or multi-line) to align how to display the text. See Android Developer documentation here for more details about android:gravity attribute.

Figure 3: Example of using gravity attribute to control text alignment


Viewing all articles
Browse latest Browse all 10

Trending Articles