안드로이드/토스트, 스낵바, 대화상자

토스트, 스낵바 그리고 대화상자 사용하기

kitty_cat 2023. 3. 18. 16:00

<토스트 메세지>

  • 간단한 메세지를 잠깐 보여주었다가 없어지는 뷰로 앱 위에 떠 있는 뷰
  • 포커스를 받지 않으므로 대화상자보다 더 쉽고 간단하게 사용할 수 있음
Toast.makeText(Context context, String message, int duration).show();
  • Context 객체는 일반적으로 Context 클래스를 상속한 액티비티를 사용할 수 있으며, 액티비티를 참조할 수 없느 ㄴ경우에는 getApplicationContext 메서드를 호출하면 객체가 반환됨.
// 토스트 뷰가 보이는 위치를 지정하는 데에 사용
public void setGravity(int gravity, int xOffset, int yOffset)
// 외부 여백을 지정하는 것으로 해당 값을 사용하여 중앙이나 우측 하단에 배치
public void setMargin(float horiziontalMargin, float verticalMargin)

 

<스낵바>

  간단한 메세지를 보여줄 때 토스트 대신 스낵바(snackbar)를 사용하는 경우도 있음.

<Button
    android:id="@+id/button4"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="12dp"
    android:onClick="onButton2Clicked"
    android:text="스낵바 띄우기"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/button3" />
  • 스낵바는 화면 아래쪽에서 올라오기 때문에 아래쪽의 화면 일부부능 라길지만 토스트와는 다른 방식으로 메세지를 보여줄 수 있다는 장점이 있음.

 

<알림 대화상자 보여주기>

  • 사용자에게 확인을 받거나 선택하게 할 때 사용된다.
  • 사용자의 입력을 받기보다는 일방적으로 메세지를 전달하는 역할을 주로 하며 예/아니오와 같은 전형적인 응답을 처리한다.
package com.example.sampledialog;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
     TextView textView;

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

        textView = findViewById(R.id.textView);

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

    // 대화상자를 만들기 위한 빌더 객체 생성
    private 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() {
           public void onClick(DialogInterface dialog, int which) {
               String message = "예. 버튼이 눌렸습니다.";
               textView.setText(message);
           }
        });
        // 취소 버튼 추가
        builder.setNeutralButton("취소", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                String message = "취소 버튼이 눌렸습니다.";
                textView.setText(message);
            }
        });
        // 아니오 버튼 추가
        builder.setNegativeButton("아니오", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                String message = "아니오 버튼이 눌렸습니다.";
                textView.setText(message);
            }
        });
        // 대화상자 객체 생성 후에 보여주기
        AlertDialog dialog = builder.create();
        dialog.show();

    }
}
  • AlertDialog는 기본 API에 포함된 것 외에 appcompat 패키지에 포함된 것도 있음.
  • AlertDialog 클래스는 알림 대화상자를 보여주는 가장 단순한 방법을 제공.
  • 알림 대화상자의 타이틀은 setTitle 메서드로 설정하고 내용은 setMessage 메서드를 사용하여 설정.
  • API에 포함된 여러 개의 아이콘 중 하나를 사용하고 싶다면 android.R.drawable을 코드에 입력해야 함.
  • 예 (setPositiveButton 메서드), 아니오 (setNegativeButton 메서드)

 

<프로그레스바 사용하기>

  • 어떤 일의 진행 상태를 중간 중간 보여줄 수 있는 가장 좋은 방법 중 하나
  • 작업의 진행 정도를 표시하거나 작업이 진행 중임을 사용자에게 알려줌.
  • 막대모앙과 원 모양
  •  
void setProgress (int progress)
void incrementProgressBy (int diff)
  • setProgress 메서드는 정수 값을 받아 프로그레스바의 현재 값으로 설정함.
  • incrementProgressBy 메서드는 현재 설정되어 있는 값을 기준으로 값을 더하거나 뺄 때 사용함.
  • 프로그레스바는 항상 보일 필요가 없기 대문에 화면에서 차지하는 공간을 줄일 수 있도록 타이틀바에 프로그래스바를 표시할 수 있음.
  •  
requestWindowFeature(Window.FEATURE_PROGRESS);
  • 타이틀 부분에 표시되는 프로그레스바는 범위를 따로 지정할 수 없음
  • 디폴트 값은 0부터 10000 사이의 값을 가질 수 있다.
  • 진행률이 50% => 값을 5000으로 설정해야 함.
  • 화면의 공간을 절약하는 매우 직관적인 방식이지만 타이틀 부분을 보이지 않게 설정하는 경우가 많으므로 사용할 수 없는 경우도 생긴다는 점을 유의
  •