Android offers a sophisticated and powerful componentized model for building your UI,
based on the fundamental layout classes: View and
ViewGroup. To start with, the platform includes a variety of prebuilt
View and ViewGroup subclasses called widgets and layouts, respectively
that you can use to construct your UI.
안드로이드는 기초적인 레이아웃 클래스인 뷰View와 뷰그룹ViewGroup에 기반해서 여러분의 UI 제작을 위한 정교하고 강력한 컴포넌트화된 모델을 제공한다. 우선 안드로이드 플랫폼은 여러분의 UI를 만드는 데 사용할 수 있는 다양한 미리 만들어진 뷰와 뷰그룹 서브클래스 - 각각은 위젯과 레이아웃이라 불린다 ? 를 포함하고 있다.
A partial list of available widgets includes Button,
TextView,
EditText,
ListView,
CheckBox,
RadioButton,
Gallery,
Spinner, and the more special-purpose
AutoCompleteTextView,
ImageSwitcher, and
TextSwitcher.
사용가능한 위젯의 일부 리스트에는 Button, TextView, EditText, ListView, CheckBox, RadioButton, Gallery, Spinner, 그리고 더 특수한 목적의 AutoCompleteTextView,ImageSwitcher, 그리고 TextSwitcher가 포함된다.
Among the layouts available are LinearLayout,
FrameLayout, RelativeLayout,
and others. For more examples, see Common Layout Objects.
사용가능한 레이아웃에 속하는 것에는 LinearLayout, FrameLayout, RelativeLayout, 그리고 그 밖의 것들이 있다. 더 많은 예제들에 대해서는 “일반적인 레이아웃 오브젝트”를 보라..
If none of the prebuilt widgets or layouts meets your needs, you can create your own View subclass. If you only need to make small adjustments to an existing widget or layout, you can simply subclass the widget or layout and override its methods.
만약 미리 만들어진 위젯 또는 레이아웃 중 어떤 것도 여러분의 필요를 충족시키지 못한다면, 여러분 자신의 뷰 서브클래스를 만들 수 있다. 만약 여러분이 기존의 위젯이나 레이아웃을 조금 개선할 필요가 있다면 여러분은 위젯 또는 레이아웃의 서브클래스를 간단히 만들어서 그것의 메쏘드를 오버라이드할 수 있다.
Creating your own View subclasses gives you precise control over the appearance and function of a screen element. To give an idea of the control you get with custom views, here are some examples of what you could do with them:
여러분 자신의 뷰 서브클래스를 만드는 것은, 스크린 엘리먼트의 모양과 기능에 대한 정확한 제어를 여러분에게 가능하게 한다. 커스텀 뷰를 사용해서 여러분이 얻을 제어에 대한 하나의 아이디어를 주기 위해, 여기에 여러분이 그것을 사용해서 할 수 있는 약간의 예제가 있다.
The sections below explain how to create custom Views and use them in your application.
For detailed reference information, see the View class.
아래의 섹션은 커스텀 뷰를 만드는 방법과 여러분의 애플리케이션에서 그것을 사용하는 방법을 설명한다. 더 자세한 레퍼런스 정보에 대해서는, 뷰View 클래스를 보라.
Here is a high level overview of what you need to know to get started in creating your own View components:
여기에 있는 것은 여러분 자신의 뷰 컴포넌트를 생성하기 위해 알아야 할 필요가 있는 것에 대한 상위 레벨에서의 개요이다.
View class or subclass
with your own class.
on', for
example, onDraw(),
onMeasure(), and
onKeyDown().
This is similar to the on... events in Activity
or ListActivity
that you override for lifecycle and other functionality hooks.
Tip: Extension classes can be defined as inner classes inside the activities that use them. This is useful because it controls access to them but isn't necessary (perhaps you want to create a new public View for wider use in your application).
Tip: 확장 클래스는 액티비티 내에 내부inner 클래스로 정의될 수 있다. 이것은 그것에 대한 접근을 통제하기 때문에 유용하다. 하지만 필수사항은 아니다(여러분은 아마 여러분 애플리케이션 내에서 더 넓게 사용할 새로운 public 뷰를 만들고자 할 것이다).
Fully customized components can be used to create graphical components that appear however you wish. Perhaps a graphical VU meter that looks like an old analog gauge, or a sing-a-long text view where a bouncing ball moves along the words so you can sing along with a karaoke machine. Either way, you want something that the built-in components just won't do, no matter how you combine them.
완전하게 커스터마이즈된 컴포넌트는, 여러분이 원하는 것이 어떤 것이든 보여줄 수 있는 그래픽컬한 컴포넌트를 제작하기 위해 사용될 수 있다. 여러분이 오래된 아날로그 게이지gauge처럼 보이는 그래픽한 VU 미터를 원하거나, 또는 여러분이 가라오케 머신을 가지고 노래할 수 있도록 단어를 따라 움직이는 바운싱bouncing 볼이 있는 sing-a-long 텍스트 뷰를 원한다고 가정하자. 어떤 쪽이든, 여러분이 원하는 것은 내장된built-in 컴포넌트를 어떻게 결합combine하더라도 할 수 없는 것이다.
Fortunately, you can easily create components that look and behave in any way you like, limited perhaps only by your imagination, the size of the screen, and the available processing power (remember that ultimately your application might have to run on something with significantly less power than your desktop workstation).
다행히도, 여러분은 원하는 방식으로 보여지고 동작하는 컴포넌트를 쉽게 만들 수 있다. 아마도 그것은 여러분의 상상력과, 스크린 크기, 그리고 사용가능한 프로세싱 파워에 의해서만 제한될 뿐이다(결국에는 여러분의 애플리케이션이 여러분의 데스크탑 워크스테이션보다는 현격하게 작은 파워를 가진 어떤 것 위에서 실행될지도 모른다는 것을 기억하라).
To create a fully customized component:
완전하게 커스터마이즈된 컴포넌트를 생성하기 위해서:
View, so you will usually start by extending this to
create your new super component.
onMeasure() and
are also likely to need to override onDraw() if you want
the component to show something. While both have default behavior,
the default onDraw() will do nothing, and the default
onMeasure() will always set a size of 100x100 which is
probably not what you want.
on... methods may also be overridden as required.
onDraw() and onMeasure()The onDraw() method delivers you a Canvas
upon which you can implement anything you want: 2D graphics, other standard or
custom components, styled text, or anything else you can think of.
onDraw() 메쏘드는 여러분에게 캔버스Convas를 파라미터로 전달하며, 그 캔버스 위에 여러분이 원하는 어떤 것, 즉 2D 그래픽, 다른 표준 또는 커스텀 컴포넌트, 스타일드styled 텍스트, 또는 그 밖의 여러분이 생각할 수 있는 어떤 것이든 구현할 수 있다.
Note:
This does not apply to 3D graphics. If you want to
use 3D graphics, you must extend SurfaceView
instead of View, and draw from a seperate thread. See the
GLSurfaceViewActivity sample
for details.
Note: 이것은 3D 그래픽에는 적용되지 않는다. 만약 여러분이 3D 그래픽을 이용하고 싶다면, 여러분은 뷰 대신에 서피스뷰(SurfaceView)를 확장해야만 하고, 별도의 쓰레드에서 그리기를 해야 한다. 보다 자세한 것에 대해서는 GLSurfaceViewActivity 예제를 보라.
onMeasure() is a little more involved. onMeasure()
is a critical piece of the rendering contract between your component and its
container. onMeasure() should be overridden to efficiently and
accurately report the measurements of its contained parts. This is made
slightly more complex by the requirements of limits from the parent
(which are passed in to the onMeasure() method) and by the
requirement to call the setMeasuredDimension() method with the
measured width and height once they have been calculated. If you fail to
call this method from an overridden onMeasure() method, the
result will be an exception at measurement time.
onMeasure()는 약간 더 복잡하다. onMeasure()는 여러분의 컴포넌트와 그것의 컨테이너 사이의 렌더링 협약의 중요한 부분이다. onMeasure()는 그것이 포함하고 있는 영역을 효과적이고 정확하게 측정해서 레포트하도록 오버라이드 되어야 한다. 이것은 (onMeasure() 메쏘드에 전달된 파라미터 안에 있는) 부모parent의 요구조건과 일단 계산되어졌던 측정된 너비measured width와 높이measured height를 가지고 setMeasuredDimension() 메쏘드를 호출하는 요구조건에 의해, 약간 더 복잡하게 만들어진다. 만약 여러분이 오버라이드한 onMeasure() 메쏘드에서 이 메쏘드를 호출하지 않는다면, 그 결과는 측정 시점에 예외exception가 될 것이다.
At a high level, implementing onMeasure() looks something
like this:
상위 레벨에서 볼 때At a high level, onMeasure()를 구현하는 것은 아래와 같이 보인다.
onMeasure() method is called with width and
height measure specifications (widthMeasureSpec and
heightMeasureSpec parameters, both are integer codes
representing dimensions) which should be treated as requirements for
the restrictions on the width and height measurements you should produce. A
full reference to the kind of restrictions these specifications can require
can be found in the reference documentation under View.onMeasure(int, int) (this reference
documentation does a pretty good job of explaining the whole measurement
operation as well).
onMeasure() method should calculate a
measurement width and height which will be required to render the
component. It should try to stay within the specifications passed in,
although it can choose to exceed them (in this case, the parent can
choose what to do, including clipping, scrolling, throwing an exception,
or asking the onMeasure() to try again, perhaps with
different measurement specifications).
setMeasuredDimension(int
width, int height) method must be called with the calculated
measurements. Failure to do this will result in an exception being
thrown.
Here's a summary of some of the other standard methods that the framework calls on views:
여기에, 뷰에서 프레임워크가 호출하는 일부 다른 표준 메쏘드들의 개요가 있다.
| Category | Methods | Description |
|---|---|---|
| Creation | Constructors | There is a form of the constructor that are called when the view is created from code and a form that is called when the view is inflated from a layout file. The second form should parse and apply any attributes defined in the layout file. |
|
Called after a view and all of its children has been inflated from XML. | |
| Layout | |
Called to determine the size requirements for this view and all of its children. |
|
Called when this view should assign a size and position to all of its children. | |
|
Called when the size of this view has changed. | |
| Drawing | |
Called when the view should render its content. |
| Event processing | |
Called when a new key event occurs. |
|
Called when a key up event occurs. | |
|
Called when a trackball motion event occurs. | |
|
Called when a touch screen motion event occurs. | |
| Focus | |
Called when the view gains or loses focus. |
|
Called when the window containing the view gains or loses focus. | |
| Attaching | |
Called when the view is attached to a window. |
|
Called when the view is detached from its window. | |
|
Called when the visibility of the window containing the view has changed. |
The CustomView sample in the API Demos provides an example of a customized View. The custom View is defined in the LabelView class.
API Demos 안에 있는 CustomView 샘플은 커스터마이징된 뷰의 예제를 제공한다. 커스텀 뷰는 LabelView 클래스에서 정의된다.
The LabelView sample demonstrates a number of different aspects of custom components:
LabelView 샘플은 커스텀 컴포넌트의 다양한 다른 측면을 보여준다.
setText(), setTextSize(),
setTextColor() and so on.onMeasure method to determine and set the
rendering size of the component. (Note that in LabelView, the real work is done
by a private measureWidth() method.)onDraw() method to draw the label onto the
provided canvas.You can see some sample usages of the LabelView custom View in
custom_view_1.xml
from the samples. In particular, you can see a mix of both android:
namespace parameters and custom app: namespace parameters. These
app: parameters are the custom ones that the LabelView recognizes
and works with, and are defined in a styleable inner class inside of the
samples R resources definition class.
여러분은 그 샘플의 custom_view_1.xml 안에서 LabelView 커스텀 뷰의 몇가지 샘플 사용법을 볼 수 있다. 특히, 여러분은 android: 네임스페이스 파라미터와 커스텀 app: 네임스페이스 파라미터 두 가지의 혼합을 볼 수 있다. 이러한 app: 파라미터는 LabelView가 인식하고 그것을 가지고 작업하는 커스텀 파라미터이며, 샘플에 대한 R 리소스 정의 클래스의 styleable 내부inner 클래스에서 정의된다.
If you don't want to create a completely customized component, but instead are looking to put together a reusable component that consists of a group of existing controls, then creating a Compound Component (or Compound Control) might fit the bill. In a nutshell, this brings together a number of more atomic controls (or views) into a logical group of items that can be treated as a single thing. For example, a Combo Box can be thought of as a combination of a single line EditText field and an adjacent button with an attached PopupList. If you press the button and select something from the list, it populates the EditText field, but the user can also type something directly into the EditText if they prefer.
만약 여러분이 완벽하게 커스터마이즈된 컴포넌트를 생성하는 것을 원하지 않고, 대신 기존에 있는 컨트롤 그룹을 구성하는 재사용가능한 컴포넌트를 함께 배치하고자 한다면, 합성 컴포넌트(혹은 합성 컨트롤)를 만드는 것이 여러분의 기대를 충족시킬 수 있다. 간단하게 말해서, 이것은 하나로 취급될 수 있는 아이템들의 논리적 그룹안에 다수의 더 원자적인atomic 컨트롤(또는 뷰)를 합쳐 놓는다. 예를 들어 콤보 박스는 단일 라인 EditText 필드에 PopupList가 붙은 인접한 버튼의 조합으로 생각될 수 있다. 만약 여러분이 버튼을 누르거나 리스트로부터 무언가를 선택한다면, 그것은 EditText 필드에 존재할 것이다. 하지만 사용자들은 또한 원하다면 EditText 안에 직접적으로 어떤 것을 입력할 수 있다.
In Android, there are actually two other Views readily available to do
this: Spinner and
AutoCompleteTextView, but
regardless, the concept of a Combo Box makes an easy-to-understand
example.
안드로이드에는, 이것을 하기 위해 이미 사용가능한 두 개의 다른 뷰가 실제로 존재한다. Spinner와 AutoCompleteTextView가 그것이다. 하지만 이와 상관없이 콤보박스 개념은 이해하기 쉬운 예제를 제공한다.
To create a compound component:
합성 컴포넌트를 생성하기 위해서:
onDraw() and onMeasure() methods since the
layout will have default behavior that will likely work just fine. However,
you can still override them if you need to.
on... methods, like
onKeyDown(), to perhaps choose certain default values from
the popup list of a combo box when a certain key is pressed.
To summarize, the use of a Layout as the basis for a Custom Control has a number of advantages, including:
요약하면, 커스텀 컨트롤에 대한 기초로 레이아웃을 사용하는 것은 다음과 같은 다양한 장점을 가진다.
onDraw() and onMeasure() methods (plus
most of the other on... methods) will likely have suitable behavior so
you don't have to override them.
In the API Demos project
that comes with the SDK, there are two List
examples Example 4 and Example 6 under Views/Lists demonstrate a
SpeechView which extends LinearLayout to make a component for displaying
Speech quotes. The corresponding classes in the sample code are
List4.java and List6.java.
SDK에 포함되어 있는 API Demos 프로젝트에서는 두 개의 리스트 예제가 있다 ? Views/Lists 아래에 있는 Example4와 Example6은 SpeechView를 보여준다. 그것은 연설문을 보여주는 컴포넌트를 만들기 위해 LinearLayout를 확장하고 있다. 샘플 코드 안의 각각에 대응되는 클래스는 List4.java와 List6.java이다.
There is an even easier option for creating a custom View which is useful in certain circumstances. If there is a component that is already very similar to what you want, you can simply extend that component and just override the behavior that you want to change. You can do all of the things you would do with a fully customized component, but by starting with a more specialized class in the View heirarchy, you can also get a lot of behavior for free that probably does exactly what you want.
어떤 상황에 유용한 커스텀 뷰를 생성하기 위한 더 쉬운 방법도 있다. 만약 여러분이 원하는 것과 매우 비슷한 컴포넌트가 이미 존재한다면, 여러분은 그 컴포넌트를 간단하게 확장extend해서 여러분이 바꾸고 싶어하는 것을 오버라이드 할 수 있다. 여러분은 완전하게 커스터마이즈된 컴포넌트를 사용해서 여러분이 원하는 모든 것을 할 수 있다. 그러나 뷰 계층구조에 더 전문화된 클래스를 사용함으로써, 여러분이 원하는 것을 아마도 정확하게 수행하는 더 많은 동작을 무상으로 또한 얻을 수 있다.
For example, the SDK includes a NotePad application in the samples. This demonstrates many aspects of using the Android platform, among them is extending an EditText View to make a lined notepad. This is not a perfect example, and the APIs for doing this might change from this early preview, but it does demonstrate the principles.
예를 들어 SDK 샘플 안에는 노트패드NotePad 애플리케이션이 포함되어 있다. 이것은 안드로이드 플랫폼을 사용하는 것의 다양한 측면을 보여준다. 그것들 중에는 밑줄이 있는 노트패드를 만들기 위해 EditText 뷰를 확장한 것이 있다. 이것은 완벽한 예제는 아니다. 그리고 이것에 대한 그 API는 이전 버전의 형태와 다르게 변경될 수도 있다. 하지만 그것은 그 원리를 설명한다.
If you haven't done so already, import the
NotePad sample into Eclipse (or
just look at the source using the link provided). In particular look at the definition of
MyEditText in the NoteEditor.java
file.
여러분이 아직 사용해 보지 않았다면, 노트패드 샘플을 이클립스 안으로 가져와라(또는 제공된 링크를 사용해 소스를 보라). 특별히 NoteEditor.java 파일에 있는 MyEditText(역주: 현재는 LineEditText로 변경되어 있음)의 정의를 살펴보라.
Some points to note here
주목할 몇 가지가 여기에 있다.
The class is defined with the following line:
public static class MyEditText extends EditText
NoteEditor
activity, but it is public so that it could be accessed as
NoteEditor.MyEditText from outside of the NoteEditor
class if desired.
static, meaning it does not generate the so-called
"synthetic methods" that allow it to access data from the parent
class, which in turn means that it really behaves as a separate
class rather than something strongly related to NoteEditor.
This is a cleaner way to create inner classes if they do not need
access to state from the outer class, keeps the generated class
small, and allows it to be used easily from other classes.
EditText, which is the View we have chosen to
customize in this case. When we are finished, the new class will be
able to substitute for a normal EditText view.
As always, the super is called first. Furthermore, this is not a default constructor, but a parameterized one. The EditText is created with these parameters when it is inflated from an XML layout file, thus, our constructor needs to both take them and pass them to the superclass constructor as well.
In this example, there is only one method to be overridden:
onDraw() but there could easily be others needed when you
create your own custom components.
For the NotePad sample, overriding the onDraw() method allows
us to paint the blue lines on the EditText view canvas (the
canvas is passed into the overridden onDraw() method). The
super.onDraw() method is called before the method ends. The
superclass method should be invoked, but in this case, we do it at the
end after we have painted the lines we want to include.
We now have our custom component, but how can we use it? In the
NotePad example, the custom component is used directly from the
declarative layout, so take a look at note_editor.xml in the
res/layout folder.
<view class="com.android.notepad.NoteEditor$MyEditText" id="@+id/note" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@android:drawable/empty" android:padding="10dip" android:scrollbars="vertical" android:fadingEdge="vertical" />
NoteEditor$MyEditText notation which is a standard way to
refer to inner classes in the Java programming language.
If your custom View component is not defined as an inner class, then you can,
alternatively, declare the View component
with the XML element name, and exclude the class attribute. For example:
<com.android.notepad.MyEditText id="@+id/note" ... />
Notice that the MyEditText class is now a separate class file. When the class
is nested in the NoteEditor class, this technique will not work.
그 클래스는 아래의 줄로 정의된다.public static class MyEditText extends EditText
항상 그렇듯이 super가 먼저 호출된다. 더 나아가, 이것은 디폴트 생성자가 아니라 파라미터화된 생성자이다. EditText는 그것이 XML 레이아웃 파일로부터 인플레이트inflate 될 때 이러한 파라미터들을 가지고 생성된다. 따라서, 우리의 생성자는 파라미터들을 얻는 것과 더불어 그것들을 슈퍼클래스 생성자에게 전달하는 것, 둘 다를 필요로 한다.
이 예제에는, 오버라이드된 하나의 메쏘드, 즉 onDraw()만이 있을 뿐이다 - 하지만 여러분 자신의 커스텀 컴포넌트를 만들 때 필요한 다른 것들이 쉽게 있을 수도 있다.
노트패드 샘플에 대해, onDraw() 메쏘드를 오버라이드하는 것은 우리가 EditText 뷰 캔버스Canvas 위에 파란색 라인을 그리는 것을 가능하게 한다(캔버스는 오버라이드된 onDraw() 메쏘드에 전달된다). super.onDraw() 메쏘드는 그 메쏘드가 끝나기 전에 불려져야 한다. 그 슈퍼클래스 메쏘드는 불려져야 한다. 하지만 이런 경우에 우리는 우리가 포함하고 싶은 선을 그린 후 끝에서 그것을 한다.
우리는 이제 우리의 커스텀 컴포넌트를 가지고 있다. 그러나 우리가 그것을 어떻게 사용할 수 있을까? 노트패드Nodepad 예제 안에서 커스텀 컴포넌트는 레이아웃 선언에서 직접 사용된다. res/layout 폴더에 있는 note_editor.xml를 살펴보라.
<view class="com.android.notepad.NoteEditor$MyEditText" id="@+id/note" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@android:drawable/empty" android:padding="10dip" android:scrollbars="vertical" android:fadingEdge="vertical" />
만약 여러분의 커스텀 뷰 컴포넌트가 내부inner 클래스로 정의되지 않는다면, 여러분은 대신에 XML 엘리먼트 이름을 가진 뷰 컴포넌트를 선언할 수 있으며, class 애트리뷰트를 제외시킬 수 있다. 예를 들어 다음과 같다.
<com.android.notepad.MyEditText id="@+id/note" ... />
MyEditText 클래스는 이제 분리된 클래스 파일이라는 것을 주의하라. 클래스가 NoteEditor 클래스에서 포함될 경우, 이 기법technique은 동작하지 않을 것이다.
And that's all there is to it. Admittedly this is a simple case, but that's the point creating custom components is only as complicated as you need it to be.
그리고 이것이 그곳에 있는 전부이다. 틀림없이 이것은 간단한 사례이다. 하지만 그것이 핵심이다 ? 커스텀 컴포넌트를 만드는 것은 여러분이 그것을 필요로 하는 만큼만 복잡해 진다.
A more sophisticated component may override even more on... methods and
introduce some of its own helper methods, substantially customizing its properties and
behavior. The only limit is your imagination and what you need the component to
do.
더 정교한 컴포넌트는 심지어 더 많은 on... 메쏘드들을 오버라이드 할 지도 모르며, 실제로 그것의 속성과 동작을 커스터마이징하여 그것 자신의 보조 메쏘드들 일부를 도입할 수 있다. 유일한 한계는 여러분의 상상력과 여러분이 그 컴포넌트로 하여금 무엇을 하도록 하느냐이다.