Kru*_*hah 13 android android-layout kotlin kotlin-android-extensions
我有以下布局:
<?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>
Run Code Online (Sandbox Code Playgroud)
当我想在下面的活动之外使用kotlin android扩展时,它不起作用.我最终做了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
Run Code Online (Sandbox Code Playgroud)
它不直接从xml中提取视图.如何在programetically inflated布局中使用它并避免findViewById
?
注意:这个问题严格属于Kotlin Android Extensions,而不是语言本身.
编辑 我已导入两个:
import kotlinx.android.synthetic.main.dialog_error.view.*
import kotlinx.android.synthetic.main.dialog_error.*
Run Code Online (Sandbox Code Playgroud)
但Android Studio仍尝试从R.id导入,但不识别这两个导入.有什么遗漏?
nha*_*man 33
如果我们想在View上调用合成属性(在适配器类中有用),我们也应该导入
Run Code Online (Sandbox Code Playgroud)kotlinx.android.synthetic.main.activity_main.view.*.
也就是说,导入kotlinx.android.synthetic.main.layout.view.*
也可以加载View
扩展属性.
然后:
val view = LayoutInflater.from(context).inflate(...)
view.tvErrorTitle.text = "test"
Run Code Online (Sandbox Code Playgroud)
它返回一个膨胀的视图:
layoutInflater.inflate(R.layout.your_layout, null)
你看,你可以更换该LayoutInflater.from(context)
本layoutInflater
在你的类从上下文超延长
归档时间: |
|
查看次数: |
16373 次 |
最近记录: |