天天看點

Android常用工具類的封裝

Android常用工具類的封裝

文章思路參考自劉桂林前輩巧用第三方快速開發AndroidApp,由衷感謝。 https://coding.imooc.com/class/81.html 這是自己在學習過程中用到的工具類,希望能幫到你,相關代碼已經上傳到Github的Util檔案夾内 https://github.com/13531982270/BlogDemo

Log封裝類

為什麼要封裝Log,這是因為我們每次輸入Log的時候,每次都要輸入TAG,例如這樣:
Log.d("tonjie","要輸出的内容");
           
即便我們可以在一個類中聲明常量TAG,private static final String TAG = "tonjies";也仍然需要輸入常量,而且很多時候我都是調試完程式,在程式沒有問題的情況下就把Log删除的,是以練習時的簡便就是我需要的,那麼廢話不多說,直接看代碼吧!
public class L {

    //TAG
    public static String TAG = "tonjies";

    //5個等級 DIWE

    public static void d(String text) {
        Log.d(TAG, text + "");
    }

    public static void i(String text) {
        Log.i(TAG, text + "");
    }

    public static void w(String text) {
        Log.w(TAG, text + "");
    }

    public static void e(String text) {
        Log.e(TAG, text + "");
    }

}
           
怎麼樣,相當簡單的代碼吧!我們隻是把每次都要輸入的TAG,提取出來,并把該值設定成預設的值罷了,讓我們來看看怎麼使用
//┏┓   ┏┓
//┏┛┻━━━┛┻┓
//┃       ┃  
//┃   ━   ┃
//┃ ┳┛ ┗┳ ┃
//┃       ┃
//┃   ┻   ┃
//┃       ┃
//┗━┓   ┏━┛
//┃   ┃  神獸保佑        
//┃   ┃  代碼無BUG!
//┃   ┗━━━┓
//┃       ┣┓
//┃       ┏┛
//┗┓┓┏━┳┓┏┛
// ┃┫┫ ┃┫┫
//
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        L.d("log列印成功");
    }
}
           
我們輸入L.d("你好,世界"),運作程式,輸入tonjies,觀察Logo,果然成功了,怎麼樣,隻輸入兩個字母的Log是不是稍微友善一點了
Android常用工具類的封裝

輸出Log

這樣封裝可能會出現一個問題,就是在不經意用了太多的L工具類,導緻輸出的東西太亂,這時候我們可以選中L類,右鍵Find Usages,或者使用快捷鍵Alt+F7,在下邊的find視窗檢視我們都在哪裡使用過,把不需要的注釋或者删除掉

sharedPreferences封裝類:

關于SharedPreferences的用法就不贅述了,詳情請檢視第一行代碼第6.4節,強烈推薦使用科學的方法檢視資料庫檔案,如facebook的 stetho ,這裡封裝的目的和封裝Log一樣,同樣是為了簡化操作,讓我們先來看看原本的用法
  • 存資料:
SharedPreferences.Editor editor=getSharedPreferences("data",MODE_PRIVATE).edit();
editor.putString("name","tonjies");
editor.putInt("age",20);
editor.apply();
           
  • 取資料:
SharedPreferences preferences = getSharedPreferences("data", MODE_PRIVATE);
String name = preferences.getString("name", "");
int age = preferences.getInt("age", 18);
L.d("name:" + name);
L.d("age" + age);
           
使用 工具檢視:
Android常用工具類的封裝

stetho工具

封裝類:
/**
 * Created by 舍長 on 2018/2/10.
 * SharedPreferences 封裝類
 */

public class ShareUtils {

    public static final String NAME = "config";


    /**
     * 存儲String類型的值
     * @param mContext this
     * @param key      key值
     * @param value    要存儲的String值
     */
    public static void putString(Context mContext, String key, String value) {
        SharedPreferences sharedPreferences = mContext.getSharedPreferences(NAME, Context.MODE_PRIVATE);
        sharedPreferences.edit().putString(key, value).commit();
    }

    /**
     * 擷取String類型的值
     * @param mContext this
     * @param key      key
     * @param defValue 預設值
     * @return
     */
    public static String getString(Context mContext, String key, String defValue) {
        SharedPreferences sharedPreferences = mContext.getSharedPreferences(NAME, Context.MODE_PRIVATE);
        return sharedPreferences.getString(key, defValue);
    }


    /**
     * 存儲Int類型的值
     * @param mContext this
     * @param key      key
     * @param value    要存儲的Int值
     */
    public static void putInt(Context mContext, String key, int value) {
        SharedPreferences sharedPreferences = mContext.getSharedPreferences(NAME, Context.MODE_PRIVATE);
        sharedPreferences.edit().putInt(key, value).commit();
    }


    /**
     * 擷取Int類型的值
     * @param mContext this
     * @param key      key
     * @param defValue 預設值
     * @return
     */
    public static int getInt(Context mContext, String key, int defValue) {
        SharedPreferences sharedPreferences = mContext.getSharedPreferences(NAME, Context.MODE_PRIVATE);
        return sharedPreferences.getInt(key, defValue);
    }


    /**
     * 存儲Boolean類型的值
     * @param mContext this
     * @param key      key
     * @param value    要存儲Boolean值
     */
    public static void putBoolean(Context mContext, String key, boolean value) {
        SharedPreferences sharedPreferences = mContext.getSharedPreferences(NAME, Context.MODE_PRIVATE);
        sharedPreferences.edit().putBoolean(key, value).commit();
    }

    /**
     * 擷取Boolean類型的值
     * @param mContext this
     * @param key      key
     * @param defValue 預設值
     * @return
     */
    public static boolean getBoolean(Context mContext, String key, Boolean defValue) {
        SharedPreferences sharedPreferences = mContext.getSharedPreferences(NAME, Context.MODE_PRIVATE);
        return sharedPreferences.getBoolean(key, defValue);
    }

    //删除 單個 key
    public static void deleShare(Context context, String key) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(NAME, Context.MODE_PRIVATE);
        sharedPreferences.edit().remove(key).commit();
    }

    //删除全部 key
    public static void deleAll(Context context) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(NAME, Context.MODE_PRIVATE);
        sharedPreferences.edit().clear().commit();
    }
}

           
我們把可複用的SharedPreferences類名和方法提取出來,并把不同的context對象,想要存儲的值 ,想要去除去除的key字段值 , 預設值等傳入,看看具體的用法吧!
  • 存資料:
//取出String類型
final String string = ShareUtils.getString(ShareActivity.this, "name", "沒有值可以取出來");
 L.d(string);
           
//取出int類型
final int age2= ShareUtils.getInt(ShareActivity.this, "age", 18);
L.d(age2+"");
           

自定義字型封裝類:

老規矩了,先看看原本應該如何實作

在src-main-asset(需要自己建立)-fonts(自己建立)-添加字型-MengYuanti.ttf

private void type() {
     Typeface typeface=Typeface.createFromAsset(getAssets(),"fonts/MengYuanti.ttf");
     txtB.setTypeface(typeface);
 }
           
Android常用工具類的封裝

添加字型檔案

/**
 * Created by 舍長 on 2018/4/27.
 */

public class FontSetting {
    public FontSetting() {
    }

    public static void setFont(Context context, TextView textView, String fontsPath) {
        try {
            Typeface fromAsset = Typeface.createFromAsset(context.getAssets(), fontsPath);
            textView.setTypeface(fromAsset);
        } catch (Exception e) {
            L.d("找不到檔案資源!");
            Toast.makeText(context, "伺服器出錯啦!", Toast.LENGTH_SHORT).show();
        }
    }
}

           
我們添加了setFont方法,并try...catch了一下,為什麼要進行異常處理呢,因為如果我們的fontPath路徑fontsPath錯誤了,比如"fonts/MengYuanti.ttf"變為了"fonts/engYuanti.ttf",程式會跑出java.lang.RuntimeException:異常,程式會崩潰、是以我們進行異常捕獲,并且告訴使用者,是伺服器出現了異常,這樣使用者的投訴就會讓伺服器人員去背,完美!
Android常用工具類的封裝

Logo.jpg

具體使用:

/**
 * Created by 舍長 on 2018/4/5.
 * 描述: Android字型設定
 */

public class FontActivity extends WinBaseActivity {
    @BindView(R.id.txt_01)
    TextView txt01;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.switch_item_layout);
        ButterKnife.bind(this);
        FontSetting.setFont(FontActivity.this,txt01,"fonts/chuxintech.woff");
    }
}
           
好了,這三個小工具類就實作到這裡了,相關代碼已經上傳到Github的androidToolPractive檔案夾了,如果關于本篇文章有什麼疑問,歡迎留言,感謝您的觀看。

繼續閱讀