03-4 토스트, 스낵바, 대화상자

코드를 만들어서 실행하다 보면 중간 중간 디버깅 메세지를 확인하거나 사용자에게 간단한 메세지를 보여줘야하는 경우가 생긴다.

디버깅을 위해서는 Log클래스를 사용해서 로그를 출력할 수 있다. 이 로그 메세지는 Logcat창에서 볼 수 있다.

사용자에게 간단한 메세지를 보여줘야하는 경우는 토스트 메세지를 사용한다. 앱 위에 떠있는 뷰라고 할 수 있다. 대화 상자도 사용자에게 정보를 알려주는 대표적인 위젯이다.

토스트는 포커스를 받지 않으므로 대화상자보다 간단하게 사용할 수 있으며, 디버깅의 목적으로도 사용할 수 있다.

특히, 앱이 사라지더라도 필요한 메세지가 그대로 표시되므로 앱의 상태와 관계없이 보여줄 수 있다는 장점이 있다.

토스트는 아래와 같이 작성한다.

Toast.make(Context context, String message, int duration).show();

Context객체는 일반적으로 Context클래스를 상속한 액티비티를 사용할 수 있으며, 액티비티를 참조할 수 없는 경우에는 getApplicationContext()메소드를 호출하면 Context객체가 반환된다.

public void setGravity(int gravity, int xOffset, int yOffset)

public void setMargin(float horizontalMargin, float verticalMargin)

setGravity() 메소드는 토스트 뷰가 보이는 위치를 지정하는 데 사용된다.

setMargin() 메소드는 토스트의 외부 여백을 지정하는 것이다.

토스트 위치 바꿔 보여주기

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity" >
    
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <EditText
            android:id="@+id/editText"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:textSize="20sp"
            android:hint="X 위치"
            android:inputType="numberSigned"/>
        
        <EditText
            android:id="@+id/editText2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:textSize="20sp"
            android:hint="Y 위치"
            android:inputType="numberSigned"/>
        
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:id="@+id/button"
            android:textSize="20sp"
            android:text="띄우기"
            android:onClick="onButton1Clicked"/>
            
    </LinearLayout>
</LinearLayout>

numberSigned 는 양수만 입력가능하게 한 것이다.

public class MainActivity extends AppCompatActivity {
    
    EditText editText;
    EditText editText2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        editText=findViewById(R.id.editText);
        editText2=findViewById(R.id.editText2);
    }

    public void onButton1Clicked(View view) {
        try{
            Toast toastView = Toast.makeText(this, "위치가 바뀐 토스트 메세지 입니다.", Toast.LENGTH_LONG);
            int xOffset = Integer.parseInt(editText.getText().toString());
            int yOffset = Integer.parseInt(editText2.getText().toString());
            
            toastView.setGravity(Gravity.TOP, xOffset, yOffset);
            toastView.show();
        }catch (NumberFormatException e){
            e.printStackTrace();
        }
    }
}

토스트 모양 바꿔 보여주기