Kotlin By id สิ่งใหม่ต้องเรียนรู้?


สวัสดีครับ วันนี้เราจะมาเรียนรู้สิ่งใหม่จากการ findViewById ของภาษา Kotlin กันนะครับว่ามีวิธีการทำจากภาษา JAVA ทั่วไปยังไงนะครับ เรามาเริ่มกันเลยครับ
การเขียนไฟล์ Xml ก็เหมือนกันทั้งสองภาษานะครับ
 <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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.todo.geekcreator.hellokotlin.MainActivity">

    <TextView
        android:id="@+id/textTest"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

การ findViewById ของภาษา Kotlin

class MyActivity : AppCompatActivity() {
    private var textTest: TextView? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        ...
        textTest = findViewById(R.id.textTest) as TextView
    }
}

การ findViewById ของภาษา Java

public class MyActivity extends AppCompatActivity {
    private TextView textTest;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        textTest = (TextView) findViewById(R.id.textTest);
    }
}

การจากศึกษาแล้วการ findViewById ของทั้งสองภาษาก็มีข้อแตกต่างกัน สามารถตามติด เพื่อรู้จักกับวิธีใหม่ๆมาอัพเดตกันนะครับ สำหรับวันนี้ก็ขอจบบทความนี้ไว้เพียงเท่านี้ครับ สำหรับวันนี้สวัสดีครับ

ความคิดเห็น

บทความที่ได้รับความนิยม