이번 시간에는 여러가지 위젯들을 다루어 볼겁니다.


안드로이드 스튜디오의 위젯은 여러가지 뜻이 있으나, 저는 오늘 버튼, 텍스트뷰 등의 위젯들을 다루어 볼 겁니다.


왼쪽 상단에 보시면 여러가지 위젯들을 보실 수 있는데요, 먼저 버튼부터 해보겠습니다.


소개해드리기 전에, 먼저 말씀드릴것이 있는데요,

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
tools:layout_editor_absoluteX="103dp"
tools:layout_editor_absoluteY="146dp" />

위와 같은 상태에서는 constraint 하지 않아서 강제로 위젯의 위치를 (0,0) 으로 옮긴다고 합니다. 이를 막기 위해서는 

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
tools:layout_editor_absoluteX="103dp"
tools:layout_editor_absoluteY="146dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"/>

위와 같은 코드가 필요합니다. 그럼 다시 본론으로 돌아가서 버튼을 한번 살펴봅시다.

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
tools:layout_editor_absoluteX="103dp"
tools:layout_editor_absoluteY="146dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"/>


이 xml 코드에서 우리는 onclick을 설정해 줄 필요가 있습니다. 이때 onclick 이란 만일 버튼이 눌렸을때 무엇을 해야 하는지 메소드를 지정해 주는 것 입니다. 그렇게 되면 

android:onClick="onclick"

코드를 추가해준 상태에서 자바 파일에서는

public void onclick(View v){

}

이러한 메소드를 코딩해 버튼이 터치되었을 시의 이벤트에 대비합니다.


또 다른 내용으로는 텍스트 뷰가 있는데요, 텍스트 뷰의 xml코드 또한 버튼의 코드와 다른점이 거의 없습니다.

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

보시면 두 위젯의 공통점을 아시겠나요? 사실 말하자면 텍스트 뷰도 버튼이 될 수 있습니다. 모든 안드로이드 위젯들이 그러합니다. 

onclick 을 설정해주는 것만으로도 이미 그 위젯을 터치했을때의 이벤트를 만들어놓은것과 같습니다. 또 텍스트를 설정하는 방법 또한 같습니다. 그렇기 때문에 버튼의 텍스트를 설정하는 방식으로 xml파일에서 텍스트 뷰의 텍스트도 설정할 수 있습니다.


여기서 제가 말하고자 함은 안드로이드 스튜디오에서 버튼만 버튼 이벤트 형성이 되는것이 아니라, 텍스트 뷰만 텍스트를 보여줄수 있는 것이 아니라는 겁니다. 그래서 필요한곳에다가 유용하게 사용할 수 있습니다.



그럼 다음시간에...

+ Recent posts