gpt4 book ai didi

android - 使用 Kotlin Android Extensions 以编程方式扩展布局

转载 作者:IT老高 更新时间:2023-10-28 13:34:36 26 4
gpt4 key购买 nike

我有以下布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
android:background="@android:color/white"
android:paddingLeft="20dp"
android:paddingRight="20dp">

<TextView
android:id="@+id/tvErrorTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:textColor="@android:color/background_dark"
android:textSize="18sp"
/>
<TextView
android:id="@+id/tvErrorDesc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:textColor="@android:color/darker_gray"
android:textSize="16sp"
/>
<TextView
android:id="@+id/tvAction"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:layout_marginBottom="10dp"
android:layout_gravity="end"
android:padding="5dp"
android:textSize="15sp"
android:textStyle="bold"
android:textAllCaps="true"
android:textColor="@android:color/holo_purple"
/>
</LinearLayout>

当我想在下面这样的 Activity 之外使用 [kotlin android extensions][1] 时,它不起作用。我最终做了 findViewById。

...
...
import kotlinx.android.synthetic.main.dialog_error.*
...
...
val view = LayoutInflater.from(context).inflate(R.layout.dialog_error, null, false)
val tvErrorTitle = view.findViewById(R.id.tvErrorTitle) as TextView
val tvErrorDesc = view.findViewById(R.id.tvErrorDesc) as TextView
val tvErrorAction = view.findViewById(R.id.tvAction) as TextView

它不会直接从 xml 中提取 View 。如何在编程膨胀布局中使用它并避免 findViewById

注意:这个问题完全属于 [Kotlin Android Extensions][1],而不是语言本身。

编辑我都进口了:

import kotlinx.android.synthetic.main.dialog_error.view.*
import kotlinx.android.synthetic.main.dialog_error.*

但 Android Studio 仍然尝试从 R.id 导入,并且无法识别这两个导入。有什么遗漏吗?[1]:https://kotlinlang.org/docs/tutorials/android-plugin.html

最佳答案

来自 docs you linked :

If we want to call the synthetic properties on View (useful in adapter classes), we should also import

kotlinx.android.synthetic.main.activity_main.view.*.

即导入 kotlinx.android.synthetic.main.layout.view.* 以及加载 View 扩展属性。

然后:

val view = LayoutInflater.from(context).inflate(...)
view.tvErrorTitle.text = "test"

关于android - 使用 Kotlin Android Extensions 以编程方式扩展布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44748350/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com