본문 바로가기
앱 개발하기

간단한 사용자 인터페이스 구축하기

by 노화방지 Anti-aging Hairstyle 2015. 12. 14.
반응형

Building a Simple User Interface   간단한 사용자 인터페이스 구축하기

 

Previous                 Next

 

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 만들기

You should also read                                    Layouts

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 fieldsViewGroup 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) 대한 단원을 참조하십시오.

 

http://developer.android.com/images/viewgroup.png

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 http://developer.android.com/images/tools/as-hide-side.png to close the Preview pane.
Preview
창에서, 숨기기 아이콘http://developer.android.com/images/tools/as-hide-side.png 클릭하여 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> 속성은 아래와 같습니다:

android:id

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 가이드를 참조하십시오.

android:hint

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 같이 콘텐츠에 맞게 됩니다.

http://developer.android.com/images/training/firstapp/edittext_wrap.png

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입니다.

http://developer.android.com/images/training/firstapp/edittext_gravity.png

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 http://developer.android.com/images/tools/as-run.png.

·        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 

 

반응형

댓글