Java之于Kotlin对比(Android)

前言

  • 通过一段时间对Kotlin的使用,总结一下Android版kotlin各种语法的写法
  • 顺便发几个常用工具类的写法,希望大家指正

正文

######1、 Thread

  • Java写法
new Thread(new Runnable() {
       @Override
       public void run() {

       }
}).start();
复制代码
  • Kotlin写法
Thread(Runnable {
               
  }).start()
复制代码

######2、Handler

  • Java
private Handler handler=new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch(msg.what){
                    case 0:
                          break;
                    default:
                          break; 
            }
            return false;
        }
    });
复制代码
  • kotlin
private val handler=Handler(Handler.Callback{msg->
    when(msg.what){
        0->{}
        else->{}
     }
    false
})
复制代码
3、setOnClickListener
  • Java
btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                
            }
});
复制代码
  • Kotlin
btn.setOnClickListener{}
复制代码
4、RadioGroup setOnCheckedChangeListener
  • Java
RadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { 
            @Override 
            public void onCheckedChanged(RadioGroup group, int checkedId) { 
                switch(checkedId){
                    case R.id.nav_bottom_menu_1:
                         break;
                    case R.id.nav_bottom_menu_2:
                         break;
                    case R.id.nav_bottom_menu_3:
                         break;
                    case R.id.nav_bottom_menu_4:
                         break;
                }
            } 
        }); 
复制代码
  • Kotlin
radioMenu.setOnCheckedChangeListener { _, checkedId ->
            when (checkedId) {
                R.id.nav_bottom_menu_1 -> {}
                R.id.nav_bottom_menu_2 -> {}
                R.id.nav_bottom_menu_3 -> {}
                R.id.nav_bottom_menu_4 -> {}
            }
        }
复制代码
5、JavaBean写法
  • Java
public class Student{
      private String name;
      private int age;
      public String getName(){
            return name;
      }
      public void setName(String name){
            this.name=name;
      }
      public String getAge(){
            return age;
      }
      public void setAge(String age){
            this.age=age;
      }
        @Override
        public String toString() {
            return "Student{" +
                "name='" + name+ '\'' +
                ", age='" + age+ '\'' +
                '}';
    }
}
复制代码
  • kotlin
data class Student(var name:String,var age:Int) {
    override fun toString(): String {
        return "Student(name='$name', age=$age)"
    }
}
//注意:
//1、声明为var类型后系统自动实现get\set方法 如果是val类型则无法用xx.name调用  
//2、该类默认实现了Student(name,age)构造器,如果想在调用中以空构造器实现,需要给该类赋初值如:
data class Student(var name:String="",var age:Int=0) {
    //::::::
}
复制代码

####常用工具类(Kotlin版本):

  • SharePreference工具类
import android.content.Context
import android.content.SharedPreferences
import android.support.v4.content.SharedPreferencesCompat

/**
 * Function:
 * author: limh
 * time:2017/7/24
 */
object SharePreferUtils {
    val FILE_NAME: String = "xxx"//文件名称

    fun put(context: Context, key: String, any: Any) {
        val sp: SharedPreferences = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE)
        val editer: SharedPreferences.Editor = sp.edit()

        if (any is String)
            editer.putString(key, any)
        else if (any is Int)
            editer.putInt(key, any)
        else if (any is Float)
            editer.putFloat(key, any)
        else if (any is Long)
            editer.putLong(key, any)
        else if (any is Boolean)
            editer.putBoolean(key, any)
        SharedPreferencesCompat.EditorCompat.getInstance().apply(editer)
    }

    fun get(context: Context, key: String, default: Any): Any {
        val sp: SharedPreferences = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE)

        if (default is String)
            return sp.getString(key, default)
        else if (default is Int)
            return sp.getInt(key, default)
        else if (default is Float)
            return sp.getFloat(key, default)
        else if (default is Long)
            return sp.getLong(key, default)
        else if (default is Boolean)
            return sp.getBoolean(key, default)
        return ""
    }

    fun putSet(context: Context, key: String, value: Set) {
        val sp: SharedPreferences = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE)
        val editer: SharedPreferences.Editor = sp.edit()
        editer.putStringSet(key, value)
        SharedPreferencesCompat.EditorCompat.getInstance().apply(editer)
    }

    fun getSet(context: Context, key: String): Set {
        val sp: SharedPreferences = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE)
        return sp.getStringSet(key, null)
    }
}
复制代码
  • Gson转换工具类
import com.google.gson.Gson
import com.google.gson.JsonArray
import com.google.gson.JsonParser
import org.json.JSONException
/**
 * Function:
 * author: limh
 * time:2017/7/11
 */
object GsonUtils {
    var gson: Gson = Gson()

    /**
     * Bean转String
     */
    fun  Gson2Str(gs: T): String {
        return gson.toJson(gs)
    }

    /**
     * string转Bean
     */
    fun  str2Bean(gsonString: String, cls: Class): T {
        return gson.fromJson(gsonString, cls)
    }

    /**
     * list转String
     */
    fun  list2Str(list: List): String {
        val arry = JsonArray()
        for (item in list)
            arry.add(Gson2Str(item))
        return arry.toString()
    }

    /**
     * str转List
     */
    fun  str2List(str: String, cls: Class): MutableList {
        val datas = ArrayList()
        try {
            val array = JsonParser().parse(str).asJsonArray
            System.out.println("数组长度=" + array.size())
            for (i in 0..array.size() - 1) {
                datas.add(str2Bean(array.get(i).asString, cls))
            }
        } catch (e: JSONException) {
            System.out.println("异常=" + e.message)
            e.printStackTrace()
        }
        return datas
    }

    /**
     * str转List
     */
    fun  str2List(str: List, cls: Class): ArrayList {
        val datas = ArrayList()
        try {
            for (item in str) {
                datas.add(str2Bean(item, cls))
            }
        } catch (e: JSONException) {
            System.out.println("异常=" + e.message)
            e.printStackTrace()
        }
        return datas
    }
}
复制代码
  • BaseActivity
abstract class BaseActivity : AppCompatActivity() {
    private var appConfig: AppConfig?=null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        findView()
        appConfig = AppConfig.getInstance()
        initViews()
        initDatas()
    }

    abstract fun findView()
    abstract fun initViews()
    abstract fun initDatas()

    /**
     * 启动一个Activity
     */
    fun openActivity(tagClass: Class<*>) {
        val intent = Intent()
        intent.setClass(this, tagClass)
        startActivity(intent)
    }

    /**
     * 启动Service
     */
    fun openService(tagClass: Class<*>) {
        val intent = Intent()
        intent.setClass(this, tagClass)
        startService(intent)
    }
    /**
     * 稍长时间展示toast
     */
    fun showToastLong(msg: String) {
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show()
    }

    /**
     * 短时间展示toast
     */
    fun showToastShort(msg: String) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
    }

    /**
     * 发送消息
     * 需要在继承的activity中定义一个handler
     * 例如:
     * private val handler = Handler(Handler.Callback { msg ->
     *
     *   false
     * })
     */
    fun sendMsg(msg: String, what: Int, handler: Handler) {
        val bundle = Bundle()
        bundle.putString("msg", msg)
        val message = Message()
        message.what = what
        message.data = bundle
        handler.sendMessage(message)
    }

    /**
     * 隐藏软件盘
     */
    fun Activity.hideKeyboard(): Boolean {
        val view = currentFocus
        view?.let {
            val inputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE)
                    as InputMethodManager
            return inputMethodManager.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
        }
        return false
    }
    override fun onDestroy() {
        super.onDestroy()
    }
}
复制代码

转载于:https://juejin.im/post/5a31dc5151882504a35efc9c

你可能感兴趣的:(Java之于Kotlin对比(Android))