Android개발(4) : EditText와 TextView를 이용한 간단한 입출력

Myeong Ho Song
Android Develop & Android
6 min readDec 27, 2014

이번 포스팅에는 안드로이드 앱에서 텍스트를 입력하고 출력하는 간단한 방법에 대해 소개하려 합니다. 이번에 쓰일 뷰는 텍스트를 입력받을 EditText와 입력받을 텍스트를 출력할 TextView, EditText에서 TextView로 텍스트를 넘겨주는 이벤트를 처리할 Button이 있습니다. 완성한 앱은 아래와 같습니다. 이번 포스팅에는 SDK버전을 21로 사용하여 원래(킷캣이나 그 이하버전) 안드로이드 ui와는 다른 ui로 나오게 되었습니다. 코드는 다른 부분이 없으므로 SDK버전에 상관없이 사용하시면 되겠습니다.

시작하기 전에 이벤트와 이벤트에 따른 처리 방식에 관하여 설명할까 합니다. 이벤트란, 뷰를 터치하거나 키누르거나 하는 행동 등을 뜻합니다. 이때 뷰는 이벤트가 일어나길 기다렸다가 이벤트가 일어날 때 행동을 합니다. 이벤트가 일어나는 것을 감지하는 부분을 리스너라 합니다.

1. EditText, Button, TextView를 사용하여 텍스트 입출력하기

위와 같은 이미지의 액티비티를 구성하기 위해 xml코드를 짜겠습니다.

<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android" android:layout_width=”match_parent” android:layout_height=”match_parent” android:orientation=”vertical”> <EditText android:id=”@+id/edittext” android:layout_width=”match_parent” android:layout_height=”wrap_content” android:hint=”Input”/> <Button android:id=”@+id/button” android:layout_height=”wrap_content” android:layout_width=”wrap_content” android:textSize=”20dp” android:text=”Insert” android:layout_gravity=”center”/> <TextView android:textSize=”20dp” android:textStyle=”bold” android:text=”Output” android:layout_width=”match_parent” android:layout_height=”wrap_content” android:id=”@+id/textview”/></LinearLayout>

EditText안에 원래 들어 있는 회색의 글자는 android:hint=””로 지정합니다.

Button 내부에 쓰여있는 글자의 경우 android:text=””를 사용하여 지정합니다. 그리고 그 텍스트의 크기를 조절하고 싶다면 android:textSize=””를 이용합니다. 이번에는 가운데 정렬을 하여 보기 좋게 했습니다.

TextView에서 텍스트를 표시하고 크기를 조정할 때는 Button과 같이 android :text=””와 android:textSize=””를 사용합니다. 그리고 텍스트의 스타일을 바꾸고 싶을 땐 android:textStyle=””를 사용합니다. 이 때 스타일은 Bold, italic, normal이 있습니다.

다음은 java코드입니다. Button을 눌렀을 때 EditText에 들어간 텍스트를 TextView로 보낼 것이므로 Button에 리스너를 만들겠습니다. onCreate()안에 들어간 부분만 보겠습니다.

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText edittext=(EditText)findViewById(R.id.edittext);
Button button=(Button)findViewById(R.id.button);
final TextView textView=(TextView)findViewById(R.id.textview);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
textView.setText(edittext.getText());
}
});
}

각각의 뷰를 선언해주고 button은 클릭했을 때 액션을 취할 것이므로 setonClickListener를 이용하여 리스너를 만듭니다. 그리고 onClick메소드 안에 버튼이 클릭되었을 때 실행될 행동을 넣습니다. textView.setText();는 TextView에 들어갈 텍스트를 설정하는 코드입니다. 그리고 edittext.getText()는 EditText에서 입력된 텍스트를 불러오는 코드입니다. 이 두 코드를 이용하여 버튼이 눌렸을 때 나올 액션을 설정해주었습니다.

2. 마무리

EditText와 Button, TextView를 이용하는 방법을 알아봤고, 리스너와 이벤트에 대해 알고 리스너를 사용했습니다. 리스너의 경우 여러 이벤트에 대해 있으므로 필요한 경우에 맞춰 리스너를 이용하시면 됩니다.

그리고 이번 포스팅에 쓰인 코드 github주소 남겨두겠습니다. 필요하시면 받아서 쓰세요~!

https://github.com/songmho/Edittext

--

--