디스플레이 메시지(toast) 만들기 (안드로이드 10버전 이후)

1. 메시지를 감싸는 배경 설정

   - res > drawable > toast_design_bg

   - 하단의 배경색상은 회색이며 모서리 부분을 둥글게 다듬었다.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
   android:shape="rectangle">

   <stroke
      android:width="3dp"
      android:color="#8C8C8C" />
      
   <solid
      android:color="#8C8C8C" />
      
   <padding
      android:left="20dp"
      android:bottom="20dp"
      android:right="20dp"
      android:top="20dp" />
      
   <corners
      android:radius="15dp" />
      
</shape>

 

2. 메시지를 표시할 layout 생성

   - layout > toast_design

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="horizontal"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:id="@+id/toast_design_root">

   <TextView
      android:id="@+id/tv_toast_design"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:background="@drawable/toast_design_bg"
      android:textColor="#FFFFFF"
      android:textSize="30dp" />
      
</LinearLayout>

 

3. 메시지 함수 생성

   - 단일 activity일 경우 편의성, 유지보수를 위해 공통함수로 사용하면 좋다.

private void displayMsg(String Msg) {
    LayoutInflater inflater = getLayoutInflater();
    
    //toast_design.xml 파일의 toast_design_root 속성을 로드
    View toastDesign = inflater.inflate(R.layout.toast_design, (ViewGroup) findViewById(R.id.toast_design_root));
    
    //메시지 표기할 디자인 가져오기
    TextView text = toastDesign.findViewById(R.id.tv_toast_design);
    
    //메시지 내용 표기
    text.setText(Msg);
    
    //메시지 크기 설정
    text.setTextSize(30);
    
    //getApplicationContext : application context (경우에 따라 this 사용 가능)
    Toast toast = new Toast(getApplicationContext());
    
    // CENTER를 기준으로 0, 0 위치에 메시지 출력
    toast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM, 0, 0);
    
    //메시지 출력 시간 : (LENGTH_SHORT : 2~3초, LENGTH_LONG : 4~5초)
    toast.setDuration(Toast.LENGTH_LONG);
    
    toast.setView(toastDesign);
    toast.show();

}

/*
	//함수호출
	displayMsg("디스플레이(토스트) 메시지 생성 테스트");
*/

 

3. 실행 예시