ViewBindinglöste das größte Problem von kotlinx.android.synthetic. In syntheticWenn Sie Ihre Inhalte im Hinblick auf eine Layout - Bindung, dann eine ID eingeben , die nur in einem anderen Layout vorhanden ist , können die IDE Sie automatisch vervollständigt und die neue Import - Anweisung hinzuzufügen. Sofern der Entwickler nicht ausdrücklich überprüft, ob seine Importanweisungen nur die richtigen Ansichten importieren, gibt es keine sichere Möglichkeit, um sicherzustellen, dass dies kein Laufzeitproblem verursacht. Aber in ViewBindingSie verwenden sollen layoutverbindlich Objekt seine Ansichten zugreifen , so dass Sie nie invoke zu einer Ansicht in einem anderen Layout und wenn Sie dies tun wollen , müssen Sie einen Compiler - Fehler nicht einen Laufzeitfehler erhalten. Hier ist ein Beispiel.
Wir erstellen zwei Layouts mit dem Namen activity_mainund activity_otherwie folgt:
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/message_main"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</RelativeLayout>
activity_other.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:id="@+id/message_other"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</RelativeLayout>
Wenn Sie Ihre Aktivität nun so schreiben:
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_other.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//Application will crash because "message_other" doesn't exist in "activity_main"
message_other.text = "Hello!"
}
}
Ihr Code wird fehlerfrei kompiliert, aber Ihre Anwendung stürzt zur Laufzeit ab. Weil die Ansicht mit der message_otherID in nicht vorhanden ist activity_mainund der Compiler dies nicht überprüft hat. Aber wenn Sie ViewBindingso verwenden:
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
//This code will never compile and the IDE shows you an error
binding.message_other.text = "Hello!"
}
}
Ihr Code wird niemals kompiliert und Android Studiozeigt Ihnen einen Fehler in der letzten Zeile.