1、创建项目的时候选择语言kotlin 其他的步骤和之前的Java开发一样
![](https://img.haomeiwen.com/i12100027/3e7a4e99abb18289.png)
![](https://img.haomeiwen.com/i12100027/34a0f2b34bd38a71.png)
2、kotlin代码如下:
class FirstActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.first_layout)
}
}
XML文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
manifest文件:
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".FirstActivity"
android:label="First app">
<intent-filter >
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
运行结果:
![](https://img.haomeiwen.com/i12100027/418fb5094d56f5c1.png)
3.在activity中经常使用的Toast
val button1:Button=findViewById(R.id.button)
button1.setOnClickListener {
Toast.makeText(this,"clicked me",Toast.LENGTH_LONG).show()
}
kotlin中在build文件的头部默认引入了一个kotlin-android-extensions插件,这个插件会根据布局将文中定义的控件id自动生成一个有相同名称的变量,所以不再需要调用findViewById()方法了
![](https://img.haomeiwen.com/i12100027/ecaacf01af91422f.png)
![](https://img.haomeiwen.com/i12100027/43a70f3873d0172a.png)
button.setOnClickListener {
Toast.makeText(this,"clicked me",Toast.LENGTH_LONG).show()
}
网友评论