美文网首页
使用kotlin创建第一个Android程序

使用kotlin创建第一个Android程序

作者: 别看后面有人 | 来源:发表于2021-06-16 16:35 被阅读0次

1、创建项目的时候选择语言kotlin 其他的步骤和之前的Java开发一样


image.png
image.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>

运行结果:


image.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()方法了


image.png
image.png
  button.setOnClickListener {
            Toast.makeText(this,"clicked me",Toast.LENGTH_LONG).show() 
        }

相关文章

网友评论

      本文标题:使用kotlin创建第一个Android程序

      本文链接:https://www.haomeiwen.com/subject/rfgxyltx.html