【问题标题】:Android Studio unable to infer type of element define in xmlAndroid Studio 无法推断 xml 中定义的元素类型
【发布时间】:2021-12-06 20:34:55
【问题描述】:

我有一个布局 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'

为什么会出错?

【问题讨论】:

标签: android android-studio android-layout type-inference


【解决方案1】:

试试这个:

val rootLayout = findViewById<ConstraintLayout>(R.id.rootLayout)

【讨论】:

  • 我的问题是为什么没有从与 rootLayout id 链接的 xml 布局中查找 ConstraintLayout。
【解决方案2】:

您必须使用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 也可以为空,或者如果您使该行不可为空,则不需要。

【讨论】:

  • 既然id rootLayout链接到xml中定义的ConstraintLayout,为什么findViewById需要再次指定类型?
【解决方案3】:

将鼠标悬停在红色下划线上应该会给您以下注释:

注意:在大多数情况下——取决于编译器的支持——结果视图会自动转换为目标类类型。如果目标类类型不受约束,则可能需要显式转换。

所以你遇到了不受约束的情况,原因在here 中解释,可以通过指定泛型类型来解决:

val rootLayout = findViewById<ConstraintLayout>(R.id.rootLayout)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 2014-05-03
    • 1970-01-01
    • 2018-02-25
    • 1970-01-01
    相关资源
    最近更新 更多