1. 程式人生 > >安卓中一些常用方法

安卓中一些常用方法

根據手機的解析度從 dp 的單位 轉成為 px(畫素) :切勿在返回值後面+0.5增加精度 因為在某些低解析度跟高分辨的手機上會有大的誤差

public static int dip2px(Context context, float dpValue) {
    final float scale = context.getResources().getDisplayMetrics().density;
    return (int) (dpValue * scale);
}
根據手機的解析度從 px(畫素) 的單位 轉成為 dp
public static int px2dip(Context context, float 
pxValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (pxValue / scale); }
SharePreference的儲存和取值
public static final void putString(Context context, String prefKey, String key, String value) {
   SharedPreferences sp = context.getSharedPreferences(prefKey, 
Context.MODE_PRIVATE); sp.edit().putString(key, value).commit(); }
public static final String getString(Context context, String prefKey, String key, String defaultValue) {
   SharedPreferences sp = context.getSharedPreferences(prefKey, Context.MODE_PRIVATE);
   return sp.getString(key, defaultValue);
}
用來判斷手機是否聯網
public static boolean isNetworkAvailable(final Context context) {
   ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
   return (networkInfo != null && networkInfo.isConnected());
}
自定義toast
public static void showToast(String msg,Context context) {
    Toast toast = new Toast(context);
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.z_toast, null);
((TextView) view.findViewById(R.id.tv)).setText(msg);
toast.setView(view);
toast.setMargin(0, 0.2f);
toast.show();
}
撥打電話
public void call(String tel) {
    Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(tel));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
隱藏鍵盤
public  void hiddenSoftInput() {
    InputMethodManager manager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}