티스토리 뷰

안드로이드 앱프로그래밍 기초

버튼 눌렀을때 메시지가 나타나게 하기

 

Empty Activity를 선택합니다.

프로젝트 이름을 입력합니다. a

ctivity_main.xml를 선택합니다.

버튼을 추가합니다.

Hello World가 적혀있는 TextView는 Delete 키를 눌러 삭제하기

<Button>태그 안에 android:onClick 속성 추가하기

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        android:onClick="onButtonClicked"
        tools:layout_editor_absoluteX="158dp"
        tools:layout_editor_absoluteY="316dp"
        tools:ignore="MissingConstraints" />

</androidx.constraintlayout.widget.ConstraintLayout>

버튼을 눌렀을 때 메시지가 나타나게 해보겠습니다.

activity_main.xml에 추가한 버튼을 MainActivity.java에 연결해야 합니다. 

그래야 버튼에서 발생한 클릭 이벤트를 자바 소스에서 처리할 수 있죠.

Toast는 작고 간단한 메시지를 잠깐 보여주는 역할을 합니다.

import 오류를 해결하려면 Alt + Enter를 눌러줍니다.

package com.jw.messageexample;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

    }

    public void onButtonClicked(View view){
        Toast.makeText(this,"Button clicked",Toast.LENGTH_LONG).show();

    }
}

app을 실행합니다.

버튼을 누르면 화면 아래에 메시지가 보였다가 사라지는 것을 확인할 수 있습니다.

 

https://youtu.be/ZOssb5T26uE

 

댓글
최근에 달린 댓글
글 보관함
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Total
Today
Yesterday
    뽀로로친구에디
    최근에 올라온 글