android開發中,你是否對錶單校驗深惡痛覺.android
是否還在寫大量的if else來校驗參數是否輸入?編程
這個文章可能能給你幫助.bash
public class SimpleParams extends HashMap<String, Object> {
//這裏放key,與校驗失敗後的提示內容
private HashMap<Object, String> checkParams = new HashMap<>();
public static SimpleParams create() {
return new SimpleParams();
}
//返回this,鏈式編程
public SimpleParams putP(String key, Object value) {
this.putP(key, value, "");
return this;
}
public SimpleParams putP(String key, Object value, String emptyMessage) {
this.put(key, value);
checkParams.put(key, emptyMessage);
return this;
}
/**
* 檢查params
*
* @param context
* @return
*/
public boolean checkValue(Context context) {
return checkValue(context, null);
}
/**
* 檢查params
*
* @param context
* @return
*/
public boolean checkValue(Context context, CheckParamsCallback checkParamsCallback) {
Set<String> strings = keySet();
for (String str : strings) {
Object value = get(str);
if (value == null || "".equals(value)) {
String s = checkParams.get(str);
//emptyMessage則說明,該參數不校驗
if (!TextUtils.isEmpty(s)) {
//傳入回調,自定義處理
if (checkParamsCallback != null) {
checkParamsCallback.callBack(s);
} else {
//默認Toast提示.
Toast.makeText(context, s, Toast.LENGTH_SHORT).show();
}
return false;
}
}
}
return true;
}
public interface CheckParamsCallback {
void callBack(String s);
}
}
複製代碼