看来我的 Android Studio 无法识别'androidx.core:core-ktx:1.2.0'
包。Android Studio 版本:3.6.1
gradle.properties
:
android.useAndroidX=true
# Automatically convert third-party libraries to use AndroidX
android.enableJetifier=true
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official
我的应用模块build.gradle
:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 29
defaultConfig {
applicationId "cz.nn.example.myapplication"
minSdkVersion 25
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8.toString()
targetCompatibility = JavaVersion.VERSION_1_8.toString()
}
kotlinOptions {
jvmTarget = "1.8"
}
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.core:core-ktx:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
}
当我尝试使用扩展功能,如:
cl MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val manager = systemService<NotificationManager>()
SharedPreferences.edit {
}
}
}
函数systemService<NotificationManager>()
和edit
无法识别。我做错了什么?

TL;博士
你用错了
首先SharedPreferences.edit()
扩展函数不是静态的,需要使用SharedPreferences
的实例。试试这个:
val prefs = getSharedPreferences("com.example.yourapp", Context.MODE_PRIVATE)
prefs.edit { putString("myString", "myValue") }
其次,该方法被称为getSystemService
,而不是systemService
。
val manager = getSystemService<NotificationManager>()
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(62条)