본문 바로가기
Android

XML과 view를 통한 사용자 인터페이스

by 아도리 2023. 2. 25.

XML은 Android에서 사용자 인터페이스를 디자인하는 데 사용되는 마크업 언어(Markup language)입니다. 뷰는 안드로이드 사용자 인터페이스의 구성 요소입니다. 콘텐츠를 표시하고 사용자 상호 작용에 응답하는 데 사용됩니다.

다음은 textview와 button이 있는 간단한 사용자 인터페이스를 정의하는 XML 레이아웃 파일의 예입니다.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/text_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click Me" />

</LinearLayout>

먼저 전체 화면을 차지하는 LinearLayout 뷰 그룹(view group)을 정의합니다. LinearLayout 내부에 두 개의 자식 뷰, 즉 TextView와 Button을 정의합니다.

TextView의 ID는 text_view이며 "Hello World!"라는 텍스트를 표시합니다. 너비가 match_parent이고 높이가 wrap_content이므로 부모의 전체 너비를 차지하고 콘텐츠에 맞게 높이가 조정됩니다.

버튼의 ID는 button이며 "Click Me"라는 텍스트를 표시합니다. 너비와 높이가 wrap_content이므로 콘텐츠에 맞게 크기가 조정됩니다.

활동에서 이 XML 레이아웃을 사용하려면 setContentView() 메서드를 사용하여 레이아웃을 인플레이트(inflate, XML을 사용할 수 있게 되는 것으로 보시면 될 것 같습니다.)해야 합니다.

다음은 간단한 활동에서 이 작업을 수행하는 방법의 예입니다.

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView textView = findViewById(R.id.text_view);
        Button button = findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textView.setText("Button clicked!");
            }
        });
    }
}

액티비티의 onCreate() 메서드에서 먼저 setContentView()를 호출하고 앞서 정의한 레이아웃 파일을 전달합니다.
그런 다음 코드에서 상호 작용할 수 있도록 findViewById()를 사용하여 TextView 및 Button 보기에 대한 참조를 가져옵니다.
마지막으로 버튼이 클릭될 때 TextView의 텍스트를 업데이트하는 OnClickListener를 버튼에 설정합니다.
XML과 뷰를 사용하면 안드로이드에서 사용자 상호 작용에 반응하는 풍부한 사용자 인터페이스를 만들 수 있습니다.

댓글