【发布时间】:2018-03-15 19:25:18
【问题描述】:
我正在尝试在对话框中操作视图,但我可以检索视图的唯一方法是使用 Java 老式方式,如下所示:
class MyDialog: DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val alert = AlertDialog.Builder(context!!)
val inflater = LayoutInflater.from(activity)
val view = inflater?.inflate(R.layout.pg_dialog, null)
with(alert) {
setView(view)
setNeutralButton(R.string.scambio_back, DialogInterface.OnClickListener({ _: DialogInterface, _: Int -> dialog.dismiss() }))
}
view?.findViewById<TextView>(R.id.dialog_name)?.text = person.name
view?.findViewById<TextView>(R.id.dialog_surname)?.text = person.surname
return alert.create()
}
}
你知道有什么方法可以在 Kotlin 中检索内部视图,避免 findViewById 吗?
[编辑] 这是 build.gradle 文件:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 27
defaultConfig {
applicationId "com.project.persons"
minSdkVersion 21
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
implementation 'com.android.support:appcompat-v7:27.0.2'
implementation 'com.android.support:recyclerview-v7:27.0.2'
implementation 'com.android.support:cardview-v7:27.0.2'
implementation 'com.android.support:design:27.0.2'
implementation 'com.android.support:support-v4:27.0.2'
// Firebase
implementation 'com.google.firebase:firebase-auth:11.8.0'
implementation 'com.google.firebase:firebase-database:11.8.0'
implementation 'com.firebaseui:firebase-ui-auth:3.2.2'
implementation 'com.facebook.android:facebook-android-sdk:4.30.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
}
apply plugin: 'com.google.gms.google-services'
【问题讨论】:
-
您是否在其他地方使用 Kotlin Android 扩展进行视图查找?这就是你想要做的吗?
-
我使用 kotlin 扩展,是的
-
查看我另一个相关问题的答案:stackoverflow.com/a/52965122/5518220
标签: kotlin findviewbyid