Android                
            토스트
        
        
            
    수색…
소개
Toast 는 작은 팝업에서 작업에 대한 간단한 피드백을 제공하며 시간이 초과되면 자동으로 사라집니다. 메시지에 필요한 공간 만 채우고 현재 활동은 계속 표시되고 대화식으로 유지됩니다.
통사론
- Toast makeText (컨텍스트 컨텍스트, CharSequence 텍스트, int 지속 기간)
 - 토스트 makeText (컨텍스트 컨텍스트, int resId, int duration)
 - void setGravity (int 중력, int xOffset, int y 오프셋)
 - void show ()
 
매개 변수
| 매개 변수 | 세부 | 
|---|---|
| 문맥 |  문맥에 토스트를 표시합니다. this 흔히 활동에 사용하고 getActivity() 일반적으로 조각에 사용된다  | 
| 본문 | Toast에 표시 할 텍스트를 지정하는 CharSequence입니다. String를 포함 해 CharSequence를 구현하는 모든 객체를 사용할 수 있습니다. | 
| resId | Toast에 표시 할 리소스 문자열을 제공하는 데 사용할 수있는 리소스 ID입니다. | 
| 지속 |  토스트가 표시되는 시간을 나타내는 정수 플래그입니다. 옵션은 Toast.LENGTH_SHORT 및 Toast.LENGTH_LONG  | 
| 중량 | 토스트의 위치 또는 "중력"을 지정하는 정수입니다. 여기 옵션보기 | 
| x 오프셋 | 토스트 위치의 수평 오프셋을 지정합니다. | 
| y 오프셋 | 토스트 위치의 수직 오프셋을 지정합니다. | 
비고
건배는 작은 팝업에서 작업에 대한 간단한 피드백을 제공합니다. 메시지에 필요한 공간 만 채우고 현재 활동은 계속 표시되고 대화식으로 유지됩니다.
Toast에 대한 가장 최근의 대안은 SnackBar입니다. SnackBar는 업데이트 된 비주얼 스타일을 제공하며 사용자가 메시지를 닫거나 추가 조치를 취할 수 있도록합니다. 자세한 내용은 SnackBar 설명서를 참조하십시오.
공식 문서 :
https://developer.android.com/reference/android/widget/Toast.html
토스트의 위치 설정
 표준 토스트 알림이 화면 중앙 하단에 정렬되어 나타납니다. setGravity(int, int, int) 사용하여이 위치를 변경할 수 있습니다. 이것은 중력 상수, x 위치 오프셋 및 y 위치 오프셋의 세 가지 매개 변수를 허용합니다. 
예를 들어, 토스트가 왼쪽 위 모서리에 나타나야한다고 결정하면 다음과 같이 중력을 설정할 수 있습니다.
toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);
        토스트 메시지 표시
안드로이드에서 Toast는 사용자에게 문맥 피드백을주는 데 사용할 수있는 간단한 UI 요소입니다.
간단한 토스트 메시지를 표시하려면 다음을 수행 할 수 있습니다.
// Declare the parameters to use for the Toast
Context context = getApplicationContext(); 
// in an Activity, you may also use "this"
// in a fragment, you can use getActivity()
CharSequence message = "I'm an Android Toast!";
int duration = Toast.LENGTH_LONG; // Toast.LENGTH_SHORT is the other option
// Create the Toast object, and show it!
Toast myToast = Toast.makeText(context, message, duration);
myToast.show();
 또는 토스트 객체를 고정하지 않고 토스트 인라인을 표시하려면 다음을 수행 할 수 있습니다.
Toast.makeText(context, "Ding! Your Toast is ready.", Toast.LENGTH_SHORT).show();
  중요 : show() 메서드가 UI 스레드에서 호출되는지 확인하십시오. 다른 스레드에서 Toast 를 표시하려는 경우 Activity runOnUiThread 메소드를 사용할 수 있습니다. 
 Toast를 작성하여 UI를 수정하려고하면 RuntimeException 이 발생합니다. 
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
 이 예외를 처리하는 가장 간단한 방법은 runOnUiThread를 사용하는 것입니다. 구문은 아래와 같습니다.
   runOnUiThread(new Runnable() {
        @Override
        public void run() {
            // Your code here
        }
    });
        커스텀 토스트 만들기
 기본 Toast보기를 사용하지 않으려면 Toast 객체에 setView(View) 메소드를 사용하여 직접 제공 할 수 있습니다. 
먼저 Toast에서 사용할 XML 레이아웃을 만듭니다.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toast_layout_root"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="8dp"
    android:background="#111">
    <TextView android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#FFF"/>
    <TextView android:id="@+id/description"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#FFF"/>
</LinearLayout>
  그런 다음 Toast를 만들 때 XML에서 사용자 정의 View를 확장하고 setView 호출합니다. 
// Inflate the custom view from XML
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast_layout,
                               (ViewGroup) findViewById(R.id.toast_layout_root));
// Set the title and description TextViews from our custom layout
TextView title = (TextView) layout.findViewById(R.id.title);
title.setText("Toast Title");
TextView description = (TextView) layout.findViewById(R.id.description);
description.setText("Toast Description");
// Create and show the Toast object
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
        토스트 (응용 프로그램 와이드) 표시 스레드 안전 방법
public class MainApplication extends Application {
    
    private static Context context; //application context
    private Handler mainThreadHandler;
    private Toast toast;
    public Handler getMainThreadHandler() {
        if (mainThreadHandler == null) {
            mainThreadHandler = new Handler(Looper.getMainLooper());
        }
        return mainThreadHandler;
    }
    @Override public void onCreate() {
        super.onCreate();
        context = this;
    }
       
    public static MainApplication getApp(){
        return (MainApplication) context;
    }
    /**
     * Thread safe way of displaying toast.
     * @param message
     * @param duration
     */
    public void showToast(final String message, final int duration) {
        getMainThreadHandler().post(new Runnable() {
            @Override
            public void run() {
                if (!TextUtils.isEmpty(message)) {
                    if (toast != null) {
                        toast.cancel(); //dismiss current toast if visible
                        toast.setText(message);
                    } else {
                        toast = Toast.makeText(App.this, message, duration);
                    }
                    toast.show();
                }
            }
        });
    }
  MainApplication 을 manifest 에 추가해야합니다. 
이제 모든 스레드에서 호출하여 축배 메시지를 표시합니다.
MainApplication.getApp().showToast("Some message", Toast.LENGTH_LONG);
        소프트 키보드 위의 토스트 메시지 표시
기본적으로 안드로이드는 키보드가 보이더라도 토스트 메시지를 화면 하단에 표시합니다. 이렇게하면 키보드 바로 위에 토스트 메시지가 표시됩니다.
public void showMessage(final String message, final int length) {
    View root = findViewById(android.R.id.content);
    Toast toast = Toast.makeText(this, message, length);
    int yOffset = Math.max(0, root.getHeight() - toast.getYOffset());
    toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, yOffset);
    toast.show();
}
        토스트 메시지를 표시하는 스레드 안전한 방법 (AsyncTask의 경우)
응용 프로그램을 확장하고 토스트 메시지를 안전하게 유지하려면, AsyncTasks의 사후 실행 섹션에 표시해야합니다.
public class MyAsyncTask extends AsyncTask <Void, Void, Void> {
    @Override
    protected Void doInBackground(Void... params) {
        // Do your background work here
    }
    @Override
    protected void onPostExecute(Void aVoid) {
        // Show toast messages here
        Toast.makeText(context, "Ding! Your Toast is ready.",   Toast.LENGTH_SHORT).show();
    }
    
}