Toast 메시지 설정
INDEX
1. Toast메시지 사용하기
2. Toast메시지 표시위치 지정하기
3. Toast메시지 삭제(취소)하기
4. Toast메시지 모양 변경하기
1. Toast메시지 사용하기
Toast메시지를 출력하기 위한 기본형식을 알아보겠습니다.
- android.widget.Toast
- public static Toast makeText( android.content.Context context, CharSequence text, int duration )
Toast.makeText( getApplicationContext(), "메시지 출력", Toast.LENGTH_SHORT ).show();
[소스] Activity.java
Argument
① Context객체
② 출력할 메시지
③ 메시지가 출력될 시간
2. Toast메시지 표시위치 지정하기
표시되는 Toast메시지의 위치를 x, y좌표로 지정할 수 있습니다.
Toast toast = Toast.makeText(getApplicationContext(), "메시지 출력", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP|Gravity.LEFT, 200, 200);
toast.show();
[소스] Activity.java
- setGravity() 메소드를 사용하여 위치를 지정할 수 있습니다.
- 형식 : setGravity( Gravity속성, x, y );
3. Toast메시지 삭제(취소)하기
Toast메시지를 빠른 시간에 연속해서 출력하는 action을 수행할 경우가 있습니다.
이때, Toast메시지는 duration시간동안 표시되기 때문에, 실제 action은 종료되었으나 메시지는 뒤늦게 계속 출력되는 경우가 발생합니다.
이를 해결하기 위해 Toast메시지 출력시, 표시되고 있는 Toast메시지를 삭제하고 표시하도록 합니다.
Toast mToast;
mToast.makeText( getApplicationContext(), "첫번째 메시지", Toast.LENGTH_SHORT ).show();
if( mToast != null ) {
mToast.cancel();
}
mToast.makeText( getApplicationContext(), "두번째 메시지", Toast.LENGTH_SHORT ).show();
[소스] Activity.java
- Toast.cancel() 메소드를 이용하여 표시되고 있는 Toast메시지를 삭제합니다.
4. Toast메시지 모양 변경하기
Toast메시지의 모양을 변경하기 위해서는 Layout으로 사용할 xml이 필요합니다.
4-1. 레이아웃을 구성할 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: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:textColor="@color/colorPrimary"
android:background="@drawable/toast"/>
</LinearLayout>
[소스] layout.xml
- android:background="@drawable/toast"
Taost의 background 모양을 변경하기 위해 drawable/toast.xml을 만들어 적용하였습니다.
4-2. 메시지 출력
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_border, (ViewGroup)findViewById(R.id.toast_layout_root));
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("new TOAST");
Toast toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP|Gravity.LEFT, 200, 200);
toast.setView(layout);
toast.show();
}
});
[소스] Activity.java
The End.
'Study > Android Studio' 카테고리의 다른 글
[Android] Confirm 메시지 사용하기 (0) | 2021.02.18 |
---|---|
[Android] Tips.쿼리 문자열로 관리하기 (0) | 2021.02.18 |
[Android] 키보드 입력언어 Default 설정하기 (0) | 2021.02.17 |
[Android] Activity를 팝업으로 띄우기 (0) | 2021.02.17 |
[Android] TextView : 문자열 속성 바꾸기 - 작성중 (0) | 2021.02.15 |