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

相关文章
相关标签/搜索