初学Kotlin之Android

第一次写博客,不足之处,敬请谅解。喷子勿看

Kotlin自从2017Google Android团队宣布成Android的第三官方编辑语言,相信大家多多少少的都有去对Kotlin做了进一步的了解,我在这里就不多说了。

下面不说废话了直接上代码 :

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    button.setOnClickListener(this)
    button1.setOnClickListener(this)

var button: Button? = null
var button1: Button? = null
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    button = findViewById<Button>(R.id.button)
    button1 = findViewById<Button>(R.id.button1)
}

fun getTabView(position: Int): View {
    val view = View.inflate(this@TestActivity, R.layout.layout_tablyout, null)
    val icon = view.findViewById<View>(R.id.tablayout_imageview) as ImageView
    val text = view.findViewById<View>(R.id.tablayout_textview) as TextView
    icon.setBackgroundResource(image[position])
    text.setText(titles[position])
    return view
}

kotlin在获取页面组件的ID时有很多方法,第一种方法其实java编译时用第三法控件有些类似,但Kotlin简单了,kotlin中使用的时候需要注意的事在gradle中必须加上

apply plugin: 'kotlin-android-extensions'

在使用的类里面必须加上

import kotlinx.android.synthetic.main.activity_test.*
activity_test这个就是你的xml布局文件;第二种和第三中其实时一样的一个是外部定义变量,一个是内部定义变量和java中的findViewById也是类似的需要注意一点就是变量的定义kotlin中可以定义无属性变量,且变量必须赋值。

class MainActivity : AppCompatActivity(), View.OnClickListener {}

Kotlin中将java中的extends和implements去掉了

override fun onClick(p0: View?) {
    when (p0?.id) {
        R.id.button ->{  
      changeBG()
      }  
    R.id.button1 ->
      intent()
    }
}

Kotlin中将java的switch替换成when,切R.id.button -> 中不能编写多行代码建议写在一个方法中(若是简单的逻辑也可以使用{}保函在内填入其中)

扫描二维码关注公众号,回复: 2201404 查看本文章

fun intent() {
     startActivity(Intent().setClass(this, TestActivity::class.java))
}

private fun changeBG() {
     bg.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark))
    
}

companion object {
    fun md5(str: String): String {
        val str = str
        var md = MessageDigest.getInstance("MD5");
        md.update(str.toByteArray())
        val digest = md.digest()
        var i = 0;
        var buf = StringBuffer("");
        for (index in digest.indices) {
            i = digest[index].toInt()
            Log.e("MD5Utils", "index = " + index + "\ni = " + i)
            if (i < 0)
                i += 256;
            if (i < 16)
                buf.append("0");
            buf.append(Integer.toHexString(i));
        }
        return buf.toString()
    }
}

Kotlin中私有方法和共有方法区别的关键字是相同的,共有方法可以省略不写。fun是创建方法的关键字,静态方法需要使用

companion object{}
包涵在内(静态变量相同),有参有返回值方法也对应的有一定使用时请参考md5加密方法

startActivity(Intent().setClass(this, TestActivity::class.java))

Kotlin中将new的关键字去掉了叫转页面时需注意activity的传入

class MyApplication : Application(){
    override fun onCreate() {
        super.onCreate()
        x.Ext.init(this)
        x.Ext.setDebug(true) //是否输出debug日志,开启debug会影响性能。
    }
}
Application的使用和java一样加在AndroidManifest.xml中

fun loginNetwork() {
    val progressDialog = ProgressDialog(this)
    progressDialog.setMessage("正在登陆...")
    progressDialog.show()
    val requestParams = RequestParams("请求地址")
    requestParams.addBodyParameter("key", "value")
    requestParams.connectTimeout = 10000
    x.http().post(requestParams, object : Callback.CommonCallback<String> {
        override fun onSuccess(result: String?) {
            Log.e(TAG, "onSuccess result = " + result)
            text.setText(result)
        }

        override fun onCancelled(cex: Callback.CancelledException?) {
            Log.e(TAG, "onCancelled cex = " + cex)
        }

        override fun onError(ex: Throwable?, isOnCallback: Boolean) {
            Log.e(TAG, "onError ex = " + ex + "\nisOnCallback = " + isOnCallback)
        }

        override fun onFinished() {
            Log.e(TAG, "onFinished")
            progressDialog.dismiss()
        }
    })
}
Kotlin中的网络请求除了post的传参稍稍有点变化其他没有变化

private var myAdapter: MyAdapter? = null
fun initViewPager() {
    myAdapter = MyAdapter(supportFragmentManager)
    pager_view.setAdapter(myAdapter)
    tab_layout.setupWithViewPager(pager_view)
    for (i in 0 until titles.size) {
        val text = tab_layout.getTabAt(i)
        if (text != null) {
            text!!.setIcon(image[i]).setText(titles[i]);
        }
        tab_layout.setTabTextColors(getResources().getColor(R.color.tab_unselected), getResources().getColor(R.color.tab_pitch_on))
    }
}

internal inner class MyAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {
    override fun getItem(position: Int): Fragment {
        return FragmentFactory.getFragment(position)
    }

    override fun getCount(): Int {
        return titles.size
    }
    
    override fun getPageTitle(position: Int): CharSequence? {
        return titles[position]
    }
}

Kotlin中ViewPager+TabLayout+Fragemnt的使用。在这里补充一点TabLayout+ViewPager知识

for (i in 0 until titles.size) {
        val text = tab_layout.getTabAt(i)
        if (text != null) {
            text!!.setIcon(image[i]).setText(titles[i]);
        }
        tab_layout.setTabTextColors(getResources().getColor(R.color.tab_unselected), getResources().getColor(R.color.tab_pitch_on))
    }

需要注意的事for()循环与java有差异,TabLayut中添加图片和文字使用的是tab_layout.getTabAt(i).setIcon().setText()方法添加,setTabTextColors()是设置选中和非选中的字体颜色,TabLayout中同时加载图片和文字时app:tabTextColor和app:tabSelectedTextColor没有作用。

Demo下载地址:https://download.csdn.net/download/duanchuanzhi/10507595

若有错误和补充欢迎大家评论栏留言

猜你喜欢

转载自blog.csdn.net/duanchuanzhi/article/details/80856020