Android 开发学习 - Kotlin

Android 开发学习 - Kotlin

  • 前言 - 最近版本上线后手上没有什么工作量就下来看看 Kotlin ,以下为学习相关内容

    以下代码的写法存在多种,这里只列举其一

       单利  java 单例模式  &  Kotlin 单例模式

       枚举  java 枚举 & Kotlin 枚举

       数据类

       Android 中常用的 Adapter Base 、 View 相关 在 Kotlin 中如何编写

       Kotlin 中对象表达式和声明

       Kotlin 中类和继承 & 接口实现

       Kotlin 中函数的声明

       Kotlin 中高阶函数与 lambda 表达式的使用

       Kotlin 中 修饰词

       Kotlin 中 控制流

       空安全 Null

下面进入正文:

java 单例模式 & Kotlin 单例模式

  • java单例模式的实现

      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 枚举

  • 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 中

              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
                      }
                  }
              }
    

数据类

  • 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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 162,710评论 4 376
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,839评论 2 308
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 112,295评论 0 255
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,776评论 0 223
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 53,198评论 3 297
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 41,074评论 1 226
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,200评论 2 322
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,986评论 0 214
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,733评论 1 250
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,877评论 2 254
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,348评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,675评论 3 265
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,393评论 3 246
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,209评论 0 9
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,996评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,212评论 2 287
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 36,003评论 2 280

推荐阅读更多精彩内容