Android 開發學習 - Kotlin

Android 開發學習 - Kotlin

  • 前言 - 最近版本上線後手上沒有什麼工做量就下來看看 Kotlin ,如下爲學習相關內容 。

    如下代碼的寫法存在多種,這裏只列舉其一java

單利  java 單例模式  &  Kotlin 單例模式

       枚舉  java 枚舉 & Kotlin 枚舉

       數據類

       Android 中經常使用的 Adapter Base 、 View 相關 在 Kotlin 中如何編寫

       Kotlin 中對象表達式和聲明

       Kotlin 中類和繼承 & 接口實現

       Kotlin 中函數的聲明

       Kotlin 中高階函數與 lambda 表達式的使用

       Kotlin 中 修飾詞

       Kotlin 中 控制流

       空安全 Null

---
下面進入正文:git

java 單例模式 & Kotlin 單例模式github

  • java單例模式的實現api

    private volatile static RequestService mRequestService;
    
    private Context mContext;
    
    public RequestService(Context context) {
        this.mContext = context.getApplicationContext();
    }
    
    public static RequestService getInstance(Context context) {
        RequestService inst = mRequestService;
        if (inst == null) {
            synchronized (RequestService.class) {
                inst = mRequestService;
                if (inst == null) {
                    inst = new RequestService(context);
                    mRequestService = inst;
                }
            }
        }
        return inst;
    }
  • Kotlin中單例模式的實現數組

    class APIService(context: Context) {
    
    protected var mContext: Context? = null
    
    init {
        mContext = context.applicationContext
    }
    
    companion object {
        private var mAPIService: APIService? = null
    
        fun getInstance(mContext: Context): APIService? {
            var mInstance = mAPIService
            if (null == mInstance) {
                synchronized(APIService::class.java) {
                    if (null == mInstance) {
                        mInstance = APIService(mContext)
                        mAPIService = mInstance
                    }
                }
            }
            return mInstance
        }
    }

    }安全

java 枚舉 & Kotlin 枚舉app

  • java 中
private enum API {

                HOME_LIST_API("homeList.api"),

                USER_INFO_API("userInfo.api"),

                CHANGE_USER_INFO_API("changeUserInfo.api"),

                private String key;

                API(String key) {
                    this.key = key;
                }

                @Override
                public String toString() {
                    return key;
                }
            }
  • Kotlin 中ide

    class UserType {函數

    private enum class API constructor(private val key: String) {
    
        HOME_LIST_API("homeList.api"),
    
        USER_INFO_API("userInfo.api"),
    
        CHANGE_USER_INFO_API("changeUserInfo.api");
    
        override fun toString(): String {
            return key
        }
    }

    }oop

數據類

  • java 中

    public class UserInfo {
    
                   private String userName;
                   private String userAge;
public void setUserName(String val){
                    this.userName = val;
                }

                public void setUserAge (String val){
                    this.userAge = val
                }

                public String getUserName(){
                    return userName;
                }

                public String getUserAge (){
                    return userAge;
                }
            }
  • Kotlin 中

    data class UserInfo(var userName: String, var userAge: String) {
               }
    
     在Kotlin 中若是想改變具體某一個值能夠這樣寫
    
               data class UserInfo(var userName: String, var userAge: Int) {
    
                   fun copy(name: String = this.userName, age: Int = this.userAge) = UserInfo(name, age)
               }
修改時能夠這樣寫

            val hy = UserInfo(name = "Hy", age = 18)
            val olderHy = hy.copy(age = 20)

Android 中經常使用的 Adapter Base 、 View 相關 在 Kotlin 中如何編寫

  • java

    public abstract class BaseAdapter<M, H extends

    RecyclerView.ViewHolder> extends RecyclerView.Adapter<H> {
    
                    protected LayoutInflater mInflater;
                    protected Context mContext;
                    protected List<M> mList;
    
                    public BaseAdapter(@Nullable Context context, @Nullable List<M> data) {
    
                        if (null == context) return;
    
                        this.mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                        this.mContext = context;
                        this.mList = data;
                    }
    
                    @Override
                    public int getItemCount() {
                        return null == mList ? 0 : mList.size();
                    }
    
                    @Override
                    public abstract H onCreateViewHolder(ViewGroup parent, int viewType);
    
                    @Override
                    public abstract void onBindViewHolder(H holder, int position);
    
                    protected String getStrings(int resId) {
                        return null == mContext ? "" : mContext.getResources().getString(resId);
                    }
            }
  • Kotlin

    abstract class BaseRecyclerAdapter<M, H : RecyclerView.ViewHolder>(
            var mContext: Context, var mList: List<M>) : RecyclerView.Adapter<H>() {
    
        override abstract fun onCreateViewHolder(parent: ViewGroup, viewType: Int): H
    
        override fun getItemCount(): Int {
            return if (null == mList) 0 else mList!!.size
        }
    
        override abstract fun onBindViewHolder(holder: H, position: Int)
protected fun getStrings(resId: Int): String {
                return if (null == mContext) "" else mContext!!.resources.getString(resId)
            }
        }

View 編寫 Java & Kotlin

  • Java

    public abstract class BaseLayout extends FrameLayout {

    public Context mContext;
    
    public LayoutInflater mInflater;
    
    public BaseLayout(Context context) {
        this(context, null);
    }
    
    public BaseLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }
    
    public BaseLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        this.mInflater = LayoutInflater.from(mContext);
    }
    
    public abstract int getLayoutId();
    
    public abstract void initView();
    
    public abstract void initData();
    
    public abstract void onDestroy();

    }

  • Kotlin

    abstract class BaseLayout(mContext: Context?) : FrameLayout(mContext) {

    /**
     * 當前 上下文
*/
            protected var mContext: Context? = null

            /**
             * contentView
             */
            private var mContentView: View? = null

            /**
             * 佈局填充器
             */
            private var mInflater: LayoutInflater? = null

            /**
             * toast view
             */
            private var mToastView: ToastViewLayout? = null

            /**
             * 這裏初始化
             */
            init {
                if (mContext != null) {
                    init(mContext)
                }
            }

            fun init(context: Context) {
                mContext = context;
                mInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater?

                initContentView()

                initView()

                initData()

                invalidate()
            }

            private fun initContentView() : Unit {
                /**
                 * 當前容器
                 */
                var mContentFrameLayout = FrameLayout(mContext)

                /**
                 * content params
                 */
                var mContentLayoutParams: ViewGroup.LayoutParams = ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)

                /**
                 * Toast params
                 */
                var mToastLayoutParams: ViewGroup.LayoutParams = ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)


                mContentView = mInflater!!.inflate(layoutId, this, false)

                /**
                 * add content view
                 */
                ViewUtils.inject(this, mContentView)
                mContentFrameLayout.addView(mContentView, mContentLayoutParams)

                /**
                 * add toast view
                 */
                mToastView = ToastViewLayout(mContext)
                ViewUtils.inject(this, mToastView)
                mContentFrameLayout.addView(mToastView, mToastLayoutParams)

                addView(mContentFrameLayout)

            }

            /**
             * 獲取 layoutId
             */
            abstract val layoutId: Int

            /**
             * 外部調用
             */
            abstract fun initView()

            /**
             * 外部調用 處理數據
             */
            abstract fun initData()

            /**
             * Toast view
             */
            class ToastViewLayout(context: Context?) : FrameLayout(context), Handler.Callback {

                private val SHOW_TOAST_FLAG: Int = 1
                private val CANCEL_TOAST_FLAG: Int = 2

                override fun handleMessage(msg: Message?): Boolean {

                    var action = msg?.what

                    when (action) {
                        SHOW_TOAST_FLAG -> ""

                        CANCEL_TOAST_FLAG -> ""
                    }
                    return false
                }

                private var mHandler: Handler? = null

                init {
                    if (null != context) {
                        mHandler = Handler(Looper.myLooper(), this)
                    }
                }

                fun showToast(msg: String) {
                    // 這裏對 toast 進行顯示

                    // 當前正在顯示, 這裏僅改變顯示內容
                    visibility = if (isShown) View.INVISIBLE else View.VISIBLE
                }

                fun cancelToast() {
                    visibility = View.INVISIBLE
                }
            }

            /**
             * 這裏對 Toast view 進行顯示
             */
            fun showToast(msg: String) {
                mToastView!!.showToast(msg)
            }

            /**
             * 這裏對 Toast view 進行關閉
             */
            fun cancelToast() {
                mToastView!!.cancelToast()
            }
        }

Kotlin 中對象表達式和聲明

在開發中咱們想要建立一個對當前類有一點小修改的對象,但不想從新聲明一個子類。java 用匿名內部類的概念解決這個問題。Kotlin 用對象表達式和對象聲明巧妙的實現了這一律念。

        mWindow.addMouseListener(object: BaseAdapter () {
            override fun clicked(e: BaseAdapter) {
                // 代碼省略
            }
        })

    在 Kotlin 中對象聲明

        object DataProviderManager {
            fun registerDataProvider(provider: DataProvider) {
                // 代碼省略
            }

            val allDataProviders: Collection<DataProvider>
                get() = // 代碼省略
        }

Kotlin 中類和繼承 & 接口實現

在 Kotlin 中聲明一個類

class UserInfo(){
        }

在 Kotlin 中 類後的()中是能夠直接定義 變量 & 對象的

class UserInfo(userName: String , userAge: Int){
        }

        class UserInfo(userType: UserType){
        }

若是不想採用這種寫法 Kotlin 中還有 constructor 關鍵字,採用 constructor 關鍵字能夠這樣寫

class UserInfo (){
            private var userName: String? = ""
            private var userAge : Int? = 0

            constructor(userName: String, userAge: Int): sueper(){
                this.userName = userName
                this.userAge  = userAge
            }
        }

Kotlin 中申明一個 接口與 Java 不相上下

interface UserInfoChangeListener {

        fun change(user: UserInfo)
    }

Kotlin 中繼承一個類 & 實現一個接口時 不用像 Java 那樣 經過 extends & implements 關鍵字, 在 Kotlin 中直接經過 : & , 來實現。

如:

        abstract BaseResut<T> {

            var code: Int? = -1
            var message: String? = ""
        }

        implements BaseCallback {

            fun callBack ()
        }

        UserInfoBean() : BaseResult<UserInfoBean> {
            // ...
        }

        // 接口實現
        UserInfoBean() : BaseCallback{

            override fun callBack(){
                // ....
            }
        }

若是當前類既須要繼承又須要實現接口 能夠這樣寫

UserInfoBean() : BaseResult<UserInfoBean> , BaseCallback {

            override fun callBack(){
                // ....
            }
        }

Kotlin 中函數的聲明

在 Java 中聲明一個函數, 模板寫法

private void readUserInfo (){
        // ...
    }

然而在 Kotlin 中直接 fun 便可

// 無返回值 無返回時 Kotlin 中經過 Unit 關鍵字來聲明 {若是 函數後沒有指明返回時  Kotlin 自動幫您完成 Unit }
    private fun readUserInfo (){
        // ...
    }

    private fun readUserInfo (): UserInfo {
        // ...
    }

Kotlin 中高階函數與 lambda 表達式的使用

在 Android 開發中的 view click 事件 可用這樣寫

mHomeLayout.setOnClickListener({ v -> createView(readeBaseLayout(0, mViewList)) })

在實際開發中咱們一般會進行各類 循環遍歷 for 、 while 、 do while 循環等。。。

在 Kotlin 中遍歷一個 集合 | 數組時 能夠經過這樣

    var mList = ArrayList<String>()

    for (item in mList) {
        // item...
    }

    這種寫法看上去沒什麼新鮮感,各類語言都大同小異 那麼在 Kotlin 中已經支持 lambda 表達式,雖然 Java  8 也支持 , 關於這點這裏就不討論了,這裏只介紹 Kotlin 中如何編寫

    val mList = ArrayList<String>()

    array.forEach { item -> "${Log.i("asList", item)}!" }

    在 Kotlin 中還有一點那就是 Map 的處理 & 數據類型的處理, 在 Java 中編寫感受非常.......
    關於 代碼的寫法差別化不少中,這裏只列表幾種經常使用的

    val mMap = HashMap<String, String>()

    第一種寫法:
        for ((k, v) in mMap) {
            // K V
        }
    第二中寫法:
        mMap.map { item -> "${Log.i("map_", + "_k_" + item.key + "_v_" + item.value)}!" }

    第三種寫法:
        mMap.mapValues { (k, v) -> Log.i("map_", "_k_" + k + "_v_" + v) }

在 Map 中查找某一個值,在根據這個值作相應的操做,在 Kotlin 中能夠經過 in 關鍵字來進行處理

如:
    val mMap = HashMap<String, String>()

    mMap.put("item1", "a")
    mMap.put("item2", "b")

    mMap.mapValues { (k , v)

        if ("item1" in k){
            // ....
            continue
        }
        // ...
    }

in 關鍵字還有一個功能就是進行類型轉換

如:

    fun getUserName (obj : Any): String{
        if (obj in String && obj.length > 0){
            return obj
        }
        return 「」
    }

Kotlin 中 修飾詞

若是沒有指明任何可見性修飾詞,默認使用 public ,這意味着你的聲明在任何地方均可見;

    若是你聲明爲 private ,則只在包含聲明的文件中可見;

    若是用 internal 聲明,則在同一模塊中的任何地方可見;

    protected 在 "top-level" 中不可使用

如:

package foo

    private fun foo() {} // visible inside example.kt

    public var bar: Int = 5 // property is visible everywhere

    private set // setter is visible only in example.kt

    internal val baz = 6 // visible inside the same module

Kotlin 中 控制流

流程控制

在 Kotlin 中,if 是表達式,好比它能夠返回一個值。是除了condition ? then : else)以外的惟一一個三元表達式

    //傳統用法
        var max = a
        if (a < b)
            max = b

        //帶 else
        var max: Int
        if (a > b)
            max = a
        else
            max = b

        //做爲表達式
        val max = if (a > b) a else b

When 表達式, Kotlin 中取消了 Java & C 語言風格的 switch 關鍵字, 採用 when 進行處理

when (index) {
        1 -> L.i("第一條數據" + index)
        2 -> L.i("第二條數據" + index)
        3 -> L.i("第三條數據" + index)
    }

空安全 Null

在許多語言中都存在的一個大陷阱包括 java ,就是訪問一個空引用的成員,結果會有空引用異常。在 java 中這就是 NullPointerException 或者叫 NPE

Kotlin 類型系統致力與消滅 NullPointerException 異常。惟一可能引發 NPE 異常的多是:

明確調用 throw NullPointerException() 外部 java 代碼引發 一些先後矛盾的初始化(在構造函數中沒初始化的成員在其它地方使用)

    var a: String ="abc"
    a = null //編譯錯誤 

如今你能夠調用 a 的方法,而不用擔憂 NPE 異常了:

val l = a.length()

在條件中檢查 null 首先,你能夠檢查 b 是否爲空,而且分開處理下面選項:

val l = if (b != null) b.length() else -1

編譯器會跟蹤你檢查的信息並容許在 if 中調用 length()。更復雜的條件也是能夠的:

// 注意只有在 b 是不可變時才能夠
    if (b != null && b.length() >0)
        print("Stirng of length ${b.length}")
    else
        print("Empty string")

安全調用 第二個選擇就是使用安全操做符,?.:

b?.length()

    // 鏈表調用
    bob?.department?.head?.name

!! 操做符

第三個選擇是 NPE-lovers。咱們能夠用 b!! ,這會返回一個非空的 b 或者拋出一個 b 爲空的 NPE

    val l = b !!.length()

安全轉換
普通的轉換可能產生 ClassCastException 異常。另外一個選擇就是使用安全轉換,若是不成功就返回空:

val aInt: Int? = a as? Int

: 關於不對的地方歡迎指出,共同窗習

最後附上GitBook地址 :https://foryueji.github.io

相關文章
相關標籤/搜索