我有一個布局 xml,其中出現以下行:
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@ id/rootLayout"
...
在 Kotline 中,我有以下行來參考此元素:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val rootLayout = findViewById(R.id.rootLayout)
...
findViewById 函式用紅色下劃線表示“沒有足夠的資訊來推斷型別變數 T”
為什么會發生這種情況。顯然型別應該是'ConstraintLayout'
為什么會出錯?
uj5u.com熱心網友回復:
試試這個:
val rootLayout = findViewById<ConstraintLayout>(R.id.rootLayout)
uj5u.com熱心網友回復:
您必須使用API level 26 (or above). 此版本已更改的簽名View.findViewById()-請參閱此處: https : //developer.android.com/about/versions/oreo/android-8.0-changes#fvbi-signature
因此,在您的情況下,在結果findViewById不明確的情況下,您需要提供型別:
1 變化:
val rootLayout = findViewById(R.id.rootLayout)
val rootLayout = findViewById<ConstraintLayout>(R.id.rootLayout)
2 變化:
this.rootLayout = row?.findViewById(R.id.rootLayout)
this.rootLayout = row?.findViewById<ConstraintLayout>(R.id.rootLayout)
請注意,在 2. 中僅需要row強制轉換,因為 可以為空。如果 也可以label為空,或者如果您使該行不可為空,則不需要它。
uj5u.com熱心網友回復:
將滑鼠懸停在紅色下劃線上應該會給您以下提示:
注意:在大多數情況下——取決于編譯器支持——結果視圖會自動轉換為目標型別別。如果目標型別別不受約束,則可能需要顯式轉換。
因此,您遇到了不受約束的情況,其原因在此處解釋并且可以通過指定泛型型別來解決:
val rootLayout = findViewById<ConstraintLayout>(R.id.rootLayout)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/329980.html
