使用kotlinx书写android实践及常见问题处理

Elysian
2021-11-04 / 0 评论 / 217 阅读 / 正在检测是否收录...

Kotlin中找不到kotlinx解决方法

在初始化Kotlin界面布局时需引用kotinx来绑定布局

import kotlinx.android.synthetic.main.activity_money.*

找不到kotlinx时在gradle文件中加入

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

kotlinx书写android实践

实现效果
1449989-32c8280866d28e63.png

如上图,想要kotlinx实现上面的效果,以为很简单,但却碰到不少的坑,毕竟还没学过kotlinx语法,不过最终还是弄出来了,在这里记录下。

准备
工欲善其事必先利其器,所以我们首先要准备好环境,在这里我使用的是AS 3.0预览版,本身就支持kotlinx,使用2.x的要装插件支持,不过我觉得使用就使用3.0吧,毕竟是亲爹支持的,新建项目什么的省了,不知道的google下...

开发
MainActivity.kt

import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v7.app.AppCompatActivity
import android.view.Menu
import android.view.MenuItem
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setSupportActionBar(toolbar)

        supportFragmentManager.beginTransaction()
                .add(R.id.fragment, MainActivityFragment(), "MainActivityFragment")
                .commit();

        fab.setOnClickListener { view ->
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show()
        }
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // Inflate the menu; this adds items to the action bar if it is present.
        menuInflater.inflate(R.menu.menu_main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        return when (item.itemId) {
            R.id.action_settings -> true
            else -> super.onOptionsItemSelected(item)
        }
    }
}

这里要注意下,由于kotlinxjava的语法风格不一样,所以要特别注意:

继承不再写extends,而是直接:表示;
使用类里面的成员或方法时,直接 supportFragmentManager.beginTransaction(),而不再 getSupportFragmentManager().beginTransaction(),很简洁;
获取控件时,没有了findViewById,而是直接使用id来引用,不过这里要注意,引入的时候记得引入 import kotlinx.android.synthetic.main.activity_main.* 这个。

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.jhworks.rxjavademo.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay"/>

    </android.support.design.widget.AppBarLayout>

    <FrameLayout android:id="@+id/fragment"
             xmlns:app="http://schemas.android.com/apk/res-auto"
             xmlns:tools="http://schemas.android.com/tools"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             app:layout_behavior="@string/appbar_scrolling_view_behavior"
             />
    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email"/>
</android.support.design.widget.CoordinatorLayout>

MainActivityFragment.mk

import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.fragment_main.*

/**
 * A placeholder fragment containing a simple view.
 */
class MainActivityFragment : Fragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_main, container, false)
    }

    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        recycler_view.layoutManager = LinearLayoutManager(context)

        val list = ArrayList<String>()
        var i: Int = 0
        while (i < 10) {
            list.add("item---" + i)
            i++
        }
        val adapter = ListAdapter(context)
        recycler_view.adapter = adapter
        adapter.setDataList(list)
    }
}

ListAdapter.kt

import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup

/**
 * @author LiaoJH
 * @VERSION 1.0
 * email: 583125288@qq.com
 * @DESC TODO
 */
class ListAdapter(context: Context) : RecyclerView.Adapter<ListHolder>() {
    private var mLayoutInflate: LayoutInflater = LayoutInflater.from(context)
    private var mDataList: List<String>? = null

    fun setDataList(dataList: List<String>) {
        mDataList = dataList
    }

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ListHolder {
        return ListHolder(mLayoutInflate.inflate(R.layout.list_item_layout, parent, false))
    }

    override fun getItemCount(): Int {
        if (mDataList == null) return 0
        else
            return mDataList?.size as Int
    }

    override fun onBindViewHolder(holder: ListHolder?, position: Int) {

        holder?.bindData(mDataList?.get(position) as String)
    }

}

list_item_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:orientation="vertical">

    <TextView
        android:id="@+id/name_tv"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:paddingLeft="20dp"
        android:gravity="center_vertical"
        android:text="Item"
        />
</LinearLayout>

ListHolder.kt

import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.TextView

/**
 * @author LiaoJH
 * @VERSION 1.0
 * email: 583125288@qq.com
 * @DESC TODO
 */
class ListHolder(itemView: View?) : RecyclerView.ViewHolder(itemView) {
    private var mNameTv: TextView = itemView?.findViewById(R.id.name_tv) as TextView

    fun bindData(name: String) {
        mNameTv.text = name
    }
}

这样就能实现开头的效果了,第一次使用kotlinx,还是有不少坑,在此记录下。

参考资料:https://www.jianshu.com/p/07fb921e1248

0

评论

博主关闭了所有页面的评论