[android]05. Toast와 대화상자

목차

  1. 토스트



토스트

토스트는 간단한 메시지로 작업에 관한 간단한 피드백을 제공합니다. 메시지에 필요한 공간만 차지하며 진행 중인 활동은 그대로 표시되고 상호작용도 유지됩니다. 토스트는 시간이 초과하면 자동으로 사라집니다.

makeText() 메서드 중에 하나를 사용하여 Toast 객체를 인스턴스화합니다. 이 메서드는 애플리케이션 Context, SMS 및 토스트의 지속 시간 이렇게 세 가지 매개변수를 사용합니다. 이 메서드는 올바르게 초기화된 토스트 객체를 반환합니다. 아래 예와 같이 show()를 사용하여 토스트 알림을 표시할 수 있습니다.

일반적인 토스트 알림은 화면 하단에 표시되며 가로로 가운데 맞춤됩니다. setGravity(int, int, int) 메서드를 사용하여 이 위치를 변경할 수 있습니다. 이 메서드는 Gravity 상수, x-좌표 오프셋y-좌표 오프셋의 세 가지 매개변수를 사용합니다.

맞춤 레이아웃을 만들려면 XML 또는 애플리케이션 코드에 뷰 레이아웃을 정의하고 루트 View 객체를 setView(View) 메서드에 전달합니다.(밑의 예제 참고)

공식 문서 - 토스트


토스트 예제

button1은 기본적인 toast를 출력합니다. button2는 모양을 변경한 toast를 출력합니다. getLayoutInflater() 메서드를 통해 LayoutInflater를 가져온 뒤 inflate를 통해 toastborder.xml을 확장합니다. toast를 설정한 뒤 출력합니다.

java 접기/펼치기
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); // activity_main 연결
        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast toast = Toast.makeText(getApplicationContext(),"hi",Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.TOP|Gravity.LEFT,0,0);
                toast.show();
            }
        });
        Button button2 = (Button) findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LayoutInflater inflater = getLayoutInflater();
                View layout = inflater.inflate(R.layout.toastborder, (ViewGroup) findViewById(R.id.toast_layout_root));
                TextView text = layout.findViewById(R.id.text);
                text.setText("모양 바꿈");
                Toast toast = new Toast(getApplicationContext());
                toast.setGravity(Gravity.CENTER, 0, -100);
                toast.setDuration(Toast.LENGTH_SHORT);
                toast.setView(layout);
                toast.show();
            }
        });
    }
}
xml 접기/펼치기
<?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="토스트"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="구운 토스트"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button" />
</androidx.constraintlayout.widget.ConstraintLayout>
toastborder.xml(새 레이아웃) 접기/펼치기
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:id="@+id/toast_layout_root">
    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="20dp"
        android:textSize="40dp"
        android:background="@drawable/toast" />
</LinearLayout>
toast.xml(shapeDrawable) 접기/펼치기
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <stroke android:width="4dp" android:color="#FFFF00"/>
    <solid android:color="#FF883300" />
    <padding android:left="20dp" android:right="20dp" android:bottom="20dp" android:top="20dp" />
    <corners android:radius="15dp" />
</shape>

0501

0502



알림 대화상자

대화상자는 사용자에게 결정을 내리거나 추가 정보를 입력하라는 프롬프트를 표시하는 작은 창입니다. 대화상자는 화면을 가득 채우지 않으며 보통은 사용자가 다음으로 계속 진행하기 전에 조치를 취해야 하는 모달 이벤트에 사용됩니다.

공식 문서 - 대화상자


알림 대화상자 예시

toast.xml(shapeDrawable) 접기/펼치기
public class MainActivity extends AppCompatActivity {

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

        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showMessage();
            }
        });
    }

    public void showMessage() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("안내");
        builder.setMessage("종료하시겠습니까?");
        builder.setIcon(android.R.drawable.ic_dialog_alert);
        builder.setPositiveButton("예", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toast.makeText(getApplicationContext(), "예", Toast.LENGTH_LONG);
            }
        });
        builder.setNegativeButton("아니오", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toast.makeText(getApplicationContext(), "아니오", Toast.LENGTH_LONG);
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }
}

0503