Building a Simple User Interface 간단한 사용자 인터페이스 구축하기
This lesson teaches you to
1. Create a Linear Layout 리니어 레이아웃 만들기
2. Add a Text Field 텍스트 필드 추가하기
3. Add String Resources 문자열 리소스 추가하기
4. Add a Button 버튼 추가하기
5. Make the Input Box Fill in the Screen Width 스크린 너비 내에 Input Box Fill 만들기
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.
이 단원에서는 XML로 텍스트 필드(text field)와 단추(button)가 포함된 레이아웃(layout)을 만듭니다. 다음 단원에서는 버튼이 눌려지면 텍스트 필드(text field)의 콘텐트가 다른 activity로 전송되어, app이 응답합니다.
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.
View와 ViewGroup 객체들(objects)의 계층구조를 이용하여 안드로이드 app의 그래픽 사용자 인터페이스를 만듭니다. View객체들은 일반적으로 buttons 또는 text fields와 같은 UI 위젯들입니다. ViewGroup객체들은, 그리드(grid) 또는 수직 목록(vertical list)으로 처럼 자식 view들의 배치방법을 정의하는 보이지 않는 view 컨테이너들 입니다.
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.
안드로이드가 View와 ViewGroup의 하위 클래스에 해당하는 XML 어휘를 제공하기 때문에, UI 엘리먼트의 계층구조를 사용하여 UI를 XML로 정의할 수 있습니다.
Layouts are subclasses of the ViewGroup. In this exercise, you'll work with a LinearLayout.
레이아웃은 ViewGroup의 하위 클래스입니다. 이 연습에서는 선형레이아웃(LinearLayout)으로 작업할 것입니다.
Alternative Layouts 대체적 레이아웃
Declaring your UI layout in XML rather than runtime code
is useful for several reasons, but it's especially important so you can create
different layouts for different screen sizes. For example, you can create two
versions of a layout and tell the system to use one on "small"
screens and the other on "large" screens. For more information, see
the class about Supporting Different Devices.
런타임 코드보다 XML로 UI 레이아웃을 선언하는 것이 여러 이유로 유용한데, 특히 중요한 것은, 서로 다른 화면크기 별로 다양한 레이아웃을 만들 수 있기 때문입니다. 예를 들어 2가지 버전의 레이아웃을 만들면, 시스템은 "작은" 화면 위에서 한 레이아웃을, "큰" 화면 위에서 다른 레이아웃을 사용할 수 있습니다. 자세한 내용은 다른 지원장치(Supporting Different Devices)에 대한 단원을 참조하십시오.
Figure 1. Illustration of how ViewGroup objects form branches in the layout and contain other View objects.
그림1. 레이아웃 안에서 ViewGroup 객체들의 가지 형성 방법과 다른 View 객체들 포함 방법 예시
Create a Linear Layout 선형 레이아웃 만들기
In Android Studio, from the res/layout directory, open the content_main.xml file.
안드로이드 스튜디오의 app/res/layout 디렉토리에서 content_main.xml 파일을 엽니다.
The BlankActivity template you chose when you created
this project includes the content_main.xml file with a RelativeLayout root view and a TextView child view.
프로젝트를 만들 때 선택한 BlankActivity
템플릿에는RelativeLayout root view와 TextView child view가 포함된 content_main.xml 파일이 포함되어 있습니다.
1.
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.
안드로이드 스튜디오에서, 레이아웃 파일인 content_main.xml 파일을 열면 가운데 아래쪽에 Design창과 Text창이 나타나는데, Text창을 클릭하면 XML파일인 content_main.xml과 Preview(미리보기) 창이 열리고, Design창을 클릭하면 Design창에 WYSIWYG 도구가 열립니다. 이 단원에서는 Design 창을 닫고 Text 창에서 XML로 직접 작업합니다.
2.
In the Preview pane,
click the Hide icon to
close the Preview pane.
Preview 창에서, 숨기기 아이콘을 클릭하여 Preview 창을 닫습니다.
3. Delete the <TextView> element. <TextView> element를 삭제하십시오.
4. Change the <RelativeLayout> element to <LinearLayout>. <RelativeLayout> element를 <LinearLayout>로 변경하십시오.
5.
Add the android:orientation attribute and set it
to "horizontal".
android:orientation 속성(attribute)을 추가한 다음, "horizontal"로 설정하십시오.
6.
Remove
the android:padding attributes and
the tools:context attribute.
android:padding 속성과 tools:context 속성을 제거하십시오.
The result looks like this: 결과는 아래와 같은 모습이 됩니다:
res/layout/content_my.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:showIn="@layout/activity_main">
</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.
LinearLayout은, android:orientation 속성에 규정된 대로, 자식 view를 수직 또는 수평 방향으로 레이아웃하는 view그룹 (ViewGroup의 하위클래스) 입니다. LinearLayout의 각
자식은, XML에 표시된 순서대로 화면에 나타납니다.
Two other attributes, android:layout_width and android:layout_height, are required for all views in order to specify their
size.
2개의 다른 속성, android:layout_width와 android:layout_height는 view들의 크기 지정 목적상 모든 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 "match_parent". This value declares that the view should
expand its width or height to match the width or height of the
parent view.
LinearLayout은 레이아웃에서 루트view이기 때문에, 너비와 높이를
"match_parent"로 정하여 앱이 사용할 수 있는 전체 화면 영역을 채워야 합니다. 이 값은 부모 view의 너비와 높이에 match되도록 너비 또는 높이를 확장해야 한다고 선언 합니다.
For more information about layout properties, see the Layout guide.
레이아웃 프로퍼티에 대한 자세한 정보는 Layout 지침서를 참조하십시오.
Add a Text Field 텍스트 필드 추가하기
As with every View object,
you must define certain XML attributes to specify the EditText object's properties.
모든 View 객체 처럼, EditText 객체의 properties를 규정하려면 XML
속성(attributes)을 정의해야 합니다.
1.
In the content_main.xml
file, within the <LinearLayout> element, define an <EditText> element with the id attribute set to @+id/edit_message.
content_main.xml 파일의 <LinearLayout> 엘리먼트 안에, id속성 세트가 @+id/edit_message로 설정된 <EditText> 엘리먼트를 정의합니다.
2.
Define
the layout_width and layout_height attributes
as wrap_content.
layout_width와 layout_height 속성을 wrap_content로 정의하십시오.
3.
Define
a hint attribute as a string object named edit_message.
hint 속성을 edit_message란 이름의 스트링 객체로 정의하십시오.
The <EditText> element should read as follows: <EditText> element는 다음과 같이 읽혀야 합니다:
res/layout/content_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: 추가한 <EditText> 속성은 아래와 같습니다:
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).
android:id는 view의 고유 식별자로써, 객체를 읽고 조작하는 것 처럼, 이 식별자를 이용하여 app코드에서 객체를 참조 할 수 있습니다(다음 단원에 나옴).
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).
at 사인(@)은 XML에서 어떤 리소스 객체를 참조할 때 요구됩니다. 리소스 타입(이 경우 id), 슬래쉬(slash), 리소스 이름 (edit_message)이 이어집니다.
Resource Objects 리소스 객체
A resource object is a unique integer name that's associated with an app
resource, such as a bitmap, layout file, or string.
리소스 객체는 비트맵(bitmap), 레이아웃 파일, 또는 문자열과 같은, app 리소스와 연결된 고유한 정수(integer)의 이름 입니다.
Every resource has a corresponding resource object defined in your project's gen/R.java file.
모든 리소스는 프로젝트의 gen/R.java 파일에 정의된 해당 리소스 객체를 갖고 있습니다.
You can use the object names in the R class to refer to your
resources, such as when you need to specify a string value for the android:hint attribute.
android:hint 속성의 문자열 값을 지정해야 할 경우, 리소스를 참조하기 위하여 R 클래스에 있는 객체 이름을 사용할 수 있습니다.
You can also create arbitrary resource IDs that you associate with a view using
the android:id attribute, which allows you to reference that view
from other code.
또한 android:id 속성을 사용하여, view와 연계시킨 임의의 리소스 ID도 생성시킬 수 있는데, 이를 이용하여 다른 코드 에서 해당 view를 참조할 수 있습니다.
The SDK tools generate the R.java file each time you compile your
app. You should never modify this file by hand.
SDK 도구는 app을 컴파일 할 때마다 R.java 파일을 생성시킵니다. 수작업으로 이 파일을 수정해서는 안됩니다.
For more information, read the guide to Providing Resources. 보다 자세한 사항은, Providing 리소스 지침서를 읽으십시오.
The plus sign (+) before the resource type is needed only
when you're defining a resource ID for the first time.
리소스 타입 앞의 더하기 기호(+)는 리소스 ID를 최초로 정의할 때만 필요합니다.
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.
app을 컴파일할 때 SDK도구는 EditText 엘리먼트를 참조하는 프로젝트의 gen/R.java 파일에 새 리소스 ID를 만들기 위하여 ID 이름을 사용합니다.
With the resource ID declared once this way, other references to the ID do not
need the plus sign.
이렇게 일단 선언된 리소스ID가 있으면, 다른 ID 참조에는 더하기 기호가 필요하지 않습니다.
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.
더하기 기호 사용은 새 리소스 ID를 지정하는 경우에만 필요하고, 문자열 또는 레이아웃과 같은 구체적 리소스 에는 필요하지 않습니다. 리소스 객체에 대한 자세한 내용은 sidebox를 참조하십시오.
android:layout_width와 android:layout_height
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.
특정 크기의 너비와 높이를 사용하는 대신, view의 내용에 맞춰 view 크기를 정하려면 "wrap_content" 값을 규정해야 합니다. "match_parent"를 사용하면, 부모 LinearLayout 크기가 되기 때문에, EditText 엘리먼트가 화면을 꽉 차게 됩니다. 자세한 내용은 Layouts 가이드를 참조하십시오.
This is a default string to display when the text field
is empty.
android:hint는 텍스트 필드가 비어 있을 때 표시하는 기본 문자열입니다.
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.
값으로 하드-코드된 문자열을 사용하는 대신, "@string/edit_message" 값은 별도 파일에 정의된 문자열 리소스를 참조 합니다.
Because this refers to a concrete resource (not just an identifier), it does
not need the plus sign.
@string/edit_message는 (단순 식별자가 아닌) 구체적 리소스를 참조하기 때문에 더하기 기호가 필요 없습니다.
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.
하지만, 아직 문자열 리소스가 정의되지 않았기 때문에 처음에는 컴파일러 오류가 나타납니다. 다음 섹션에서 문자열을 정의하여 수정합니다.
Note: This string
resource has the same name as the element ID: edit_message. However,
references to resources are always scoped by the resource type (such
as id or string), so using the same name does not cause
collisions.
참고: 이 문자열 리소스는 ID: edit_message 엘리먼트와 이름이 같습니다. 하지만, 리소스에 대한 참조는 항상 리소스 종류(id 또는 문자열 등)에 의해 범위가 정해지기 때문에 동일한 이름을 사용해도 충돌이 발생되지 않습니다.
Add String Resources 문자열 리소스 추가하기
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."
기본적으로, 안드로이드 프로젝트에는 res/values/strings.xml에 스트링 리소스 파일이 포함됩니다. 여기서, "edit_message"란 이름의 새로운 스트링을 추가하고 "Enter a message"를 그 값으로 설정합니다.
1.
In Android Studio,
from the res/values directory, open strings.xml.
안드로이드 스튜디오의 res/values 디렉토리에서 strings.xml을 여십시오.
2.
Add a line for a
string named "edit_message" with the value, "Enter a
message".
이름이 "edit_message"이고, 값이 "Enter a message"인 문자열 줄을 추가하십시오.
3.
Add a line for a
string named "button_send" with the value,
"Send".
이름이 "button_send"이고 값이 "Send"인 문자열 줄을 추가하십시오.
You'll create the button that uses this string in the next section.
다음 섹션에서 이 문자열을 사용하는 버튼을 만들어봅니다.
The result for strings.xml looks like this: strings.xml의 결과는 아래와 같습니다:
res/values/strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">My Application</string>
<string name="action_settings">Settings</string>
<string name="edit_message">Enter a message</string>
<string name="button_send">Send</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.
문자열 리소스를 사용하면 단일 위치에서 모든 UI 텍스트를 관리할 수 있어서, 텍스트를 보다 쉽게 찾아서 업데이트 할 수 있습니다.
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.
다른 언어에 대한 앱의 지역화를 위한, 문자열 리소스 사용에 관한 자세한 사항은 Supporting Different Devices 클래스를 참조하십시오.
Add a Button 버튼 추가하기
1.
In Android Studio, from
the res/layout directory, edit the activity_my.xml file.
안드로이드 스튜디오의, res/layout 디렉토리에서, content_main.xml
파일을 편집하십시오.
2.
Within the <LinearLayout> element, define a <Button> element immediately following the <EditText>element.
<LinearLayout> 엘리먼트의 <EditText>
엘리먼트 바로 뒤에 <Button> 엘리먼트를 정의하십시오.
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.
버튼의 너비와 높이 속성을 "wrap_content"로 설정하면 버튼은 버튼의 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.
버튼의 text label을 android:text 속성으로 정의하십시오; 앞 섹션에서 정의한 button_send 문자열 리소스에 그 값을 설정하십시오.
Your <LinearLayout> should look like this: <LinearLayout> 는 아래와 같습니다:
res/layout/content_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.
참조: 이 버튼은 android:id 속성이 필요 없는데, 그 이유는 activity 코드에서 이것을 참조하지 않기 때문입니다.
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.
현재 레이아웃이 설계되어 있기 때문에, EditText와 Button 위젯의 크기는 그림2와 같이 그 콘텐츠에 맞게 됩니다.
Figure 2. The EditText and Button widgets have their widths set to "wrap_content".
그림2. EditText와 Button 위젯의 너비가
"wrap_content"에 맞추어졌습니다.
This works fine for the button, but not as well for the text field, because
the user might type something longer.
wrap_content가 버튼에게는 잘 작동하지만 텍스트 필드에는 작동하지 않는데, 사용자가 뭔가를 더 타입할 수 있기 때문입니다.
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.
weight 프로퍼티를 가진 LinearLayout 안에서 android:layout_weight 속성을 사용하여 빈 화면 너비를 채우도록 규정할 수 있습니다.
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.
weight value는 각 view가 차지해야 하는, 형제 view가 차지한 너비와 관련된, 남은 너비를 지정하는 숫자입니다.
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.
이것은 음료 레시피의 재료 양처럼 작동합니다: "2부분의 소다, 1부분의 시럽"은 음료의 3분의2가 소다 임을 의미합니다.
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.
예를 들어, 한 view에게 weight에 2를 주고, 다른 하나에게 1의 weight를 준다면, 합은 3이기 때문에 첫째 view는 남은 너비의 2/3를 채우고 두 번째 view는 나머지 너비를 채웁니다.
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.
세 번째 view를 추가하고 1의 무게를 준다면, 첫 번째 view(weight가 2인)는, 나머지 2개가 각각 1/4을 얻는 동안, 남은 영역의 1/2을 얻습니다.
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.
모든 view의 default weight는 0이기 때문에, 모든 weight value를 1개의 view에 대하여 0보다 크게 지정한다면, 해당 view는 모든 views가 요구하는 너비를 부여한 후 남은 너비를 채웁니다.
Make the Input Box Fill in the Screen Width 화면 너비로 Input Box를 채우기
To fill the remaining space in your layout with the EditText element, do the following:
layout안의 남은 영역을 EditText element로 채우려면, 다음과 같이 하십시오:
1.
In the activity_my.xml file,
assign the <EditText> element's layout_weight attribute a value of 1.
content_main.xml파일에서, <EditText> element의 layout_weight 속성에 1의 값을 할당하십시오.
2.
Also, assign <EditText> element's layout_width attribute a value of 0dp.
또한, <EditText> element의 layout_width 속성에 0의 값을 할당하십시오.
res/layout/content_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).
weight를 규정할 때 레이아웃 효율성을 향상시키기 위하여, EditText의 너비를
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.
너비를 0으로 설정하면 레이아웃 성능이 향상되는데, 그 이유는 weight value가 나머지 공간을 채우기 위해 다른 너비 계산을 요구하기 때문에, 시스템이 궁극적으로 무관한 너비를 계산하기 위하여
"wrap_content"을 사용하기 때문입니다.
Figure 3 shows the result when you assign all weight to the EditText element. EditText 엘리먼트에 모든 weight를 부여할 때의 결과는 그림3입니다.
Figure 3. The EditText widget is given all the layout weight, so it fills the remaining
space in the LinearLayout.
그림3. EditText 위젯에 모든 layout weight가 부여되어, 이것이 LinearLayout의 나머지 공간을 채웁니다.
Here’s how your complete content_main.xml layout file should now
look:
content_main.xml layout 파일을 완성하는 방법은 아래와 같습니다:
res/layout/content_main.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
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:
이 layout은, 프로젝트를 생성했을 때 SDK 도구가 만든, default Activity class에 의하여 적용됩니다. 결과를 보기 위하여 app을 Run하십시오:
· In Android Studio, from the toolbar, click Run .
· 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.
Next: Starting Another Activity
'앱 개발하기' 카테고리의 다른 글
다른 Activity 시작하기 (0) | 2015.12.14 |
---|---|
앱(app) 가동하기 (0) | 2015.12.14 |
안드로이드 프로젝트 만들기 (0) | 2015.12.14 |
안드로이드 스튜디오는 안드로이드 앱을 개발하는 공식 IDE 입니다 (0) | 2015.12.14 |
안드로이드 스튜디오 설치하기 (0) | 2015.12.14 |
댓글