Kotlin Android项目构建初体验 6-13
本文致力于从0-1构建一个基于Kotlin开发的Android项目,项目会涉及到Kotlin的环境配置以及各种第三方框架的调用,有网络访问的AsyncHttp以及免费短信验证SMSSDK等等。
话不多说,从项目构建开始。由于Android Studio3.0中已经集成了Kotlin,所以在构建项目时只需要勾上即可,如图

接下来从登录界面开始编写,首先编写已个简单的登录界面。代码如下
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2">
android:id="@+id/Icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="0dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:layout_weight="3">
android:id="@+id/username"
android:layout_width="match_parent"
android:layout_height="52dp"
android:hint="Username"/>
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="52dp"
android:layout_marginTop="10dp"
android:inputType="textPassword"
android:hint="Password"/>
android:id="@+id/login"
android:text="登录"
android:layout_width="match_parent"
android:background="@drawable/shape"
android:textColor="#fff"
android:layout_marginTop="20dp"
android:layout_height="52dp"/>
打开Preview发现存在错误,看不见编写的xml布局
错误如下:

根据这个错误,预判到可能是ActionBar的问题,我们找到style.xml,找到使用的application主题:
<stylename="AppTheme"parent="Theme.AppCompat.Light.DarkActionBar">
修改成
<stylename="AppTheme"parent="Base.Theme.AppCompat.Light">
然后回到xml界面 刷新即可。
同时 为了充分使用kotlin的优势,需要用到其插件
在project的build.gradle 中加入kotlin-android-extensions插件:
classpath"org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"//拓展插件,用于拓展绑定关系
同时在app的build.gradle中加入
applyplugin:'kotlin-android-extensions'// kotlin-android-extensions用于扩展绑定关系
然后就能在愉快的使用Id调用控件了,代码如下
importandroid.app.Activity
importandroid.os.Bundle
importandroid.widget.Toast
importkotlinx.android.synthetic.main.activity_main.*
classMainActivity :Activity() {
override funonCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
login.setOnClickListener({
if(username.text.length==0||password.text.length==0){
Toast.makeText(this,"信息输入不完整",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this,"UserName${username.text}password+${password.text}",Toast.LENGTH_SHORT).show();
} }) } }
界面如下:

第一次发布 不足之处望指正。