안드로이드에서 가장많이 사용하는 Widget중에 하나가 Toast입니다.
Toast는 기본적으로 SHORT(2초), LONG(3.5초) duration 만을 제공하고 있으면, 대체로 의미있는 표시를 할 수 있습니다. 간단하게 Toast를 사용하는 형태와, 첨부된 ToastUtil 클래스의 사용 형태를 살펴보면 아래와 같습니다.
기본 예)
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
ToastUtil 예)
ToastUtil.show(context, message);
안드로이드 API가 대체로 긴 클래스와 메소드가 많아서 코드의 가독성을 떨어트리는 경향이 있는데, 이런 유틸리티 클래스등으로 가독성을 높일 수 있습니다. 그리고, SHORT, LONG만이 아니, 개발자가 duration을 지정할 수있는 기능도 있습니다.
* ToastUtil.java
package net.sjava.toast;
import android.content.Context;
import android.os.CountDownTimer;
import android.widget.Toast;
public class ToastUtil {
/**
* 2초
* @param c
* @param message
*/
public static void show(Context c, String message) {
if(c == null || StringUtil.isEmpty(message))
return;
try {
Toast.makeText(c, message, Toast.LENGTH_SHORT).show();
} catch(Exception e) {
// ignore
}
}
/**
* 3.5 초
* @param c
* @param message
*/
public static void showLong(Context c, String message) {
if(c == null || StringUtil.isEmpty(message))
return;
try {
Toast.makeText(c, message, Toast.LENGTH_LONG).show();
} catch(Exception e) {
// ignore
}
}
/**
* 커스텀..
* @param c
* @param message
* @param miliseconds
*/
public static void show(final Context c, final String message, int miliseconds) {
if(c == null || StringUtil.isEmpty(message))
return;
int duration = miliseconds;
if(duration < 2000)
duration = 2000;
final Toast t = Toast.makeText(c, message, Toast.LENGTH_SHORT);
new CountDownTimer(duration, 1000) {
@Override
public void onTick(long millisUntilFinished) {
t.show();
}
@Override
public void onFinish() { }
}.start();
}
}
* StringUtil.java
package net.sjava.toast;
public class StringUtil {
public static boolean isEmpty(String str) {
if(str == null || str.trim().length() ==0)
return true;
return false;
}
public static boolean isAnyEmpty(String str1, String str2) {
if(isEmpty(str1) || isEmpty(str2))
return true;
return false;
}
public static boolean isAllEmpty(String str1, String str2) {
if(isEmpty(str1) && isEmpty(str2))
return true;
return false;
}
}