首页 > 解决方案 > 未解决的参考:Kotlin 上的 LayoutParams

问题描述

我无法将我们的函数从 Java 语言转换为 Kotlin。我用了AS 3.2.1

这是我在 Java 上的功能

private class ImageViewFactory implements ViewSwitcher.ViewFactory {
    @Override
    public View makeView() {
        final ImageView imageView = new ImageView(MainActivity.this);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

        final LayoutParams lp = new ImageSwitcher.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        imageView.setLayoutParams(lp);

        return imageView;
    }
}

在 kotlin 中如下所示

private inner class ImageViewFactory : ViewSwitcher.ViewFactory {
    override fun makeView(): View {
        val imageView = ImageView(this@MainActivity)
        imageView.scaleType = ImageView.ScaleType.CENTER_CROP

        val lp =
            ImageSwitcher.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
        imageView.layoutParams = lp

        return imageView
    }
}

问题来自ImageSwitcher.LayoutParams,在 Java 上它的工作很好。但不幸的是,Kotlin 无法识别这些功能。

这里是我的 Java Apps gradle

android {
    compileSdkVersion 26
    buildToolsVersion '27.0.3'

    defaultConfig { 
        minSdkVersion 19
        targetSdkVersion 26

implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation project(':card-slider')

    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'
    implementation 'com.android.support:design:26.1.0'
    implementation 'com.android.support:recyclerview-v7:26.1.0'
    implementation 'com.android.support:cardview-v7:26.1.0'

从我的 Kotlin Gradle 中咆哮

android {
    compileSdkVersion 26
    defaultConfig { 
        minSdkVersion 19
        targetSdkVersion 26

implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'
    implementation 'com.android.support:design:26.1.0'
    implementation 'com.android.support:recyclerview-v7:26.1.0'
    implementation 'com.android.support:cardview-v7:26.1.0'

    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.facebook.android:facebook-login:[4,5)'
    implementation 'com.ramotion.cardslider:card-slider:0.3.0'

它在 Android Studio 上显示语法错误Unresolved references : LayoutParams

我不确定它发生了什么。请让我知道我错过了什么。谢谢

标签: javaandroidkotlin

解决方案


当您想要转换JavaKotlin无法解析参考时。只需看一下Java文件的导入部分,然后您就可以找到应该在Kotlin文件中导入哪一个。

对于您的问题,LayoutParams是从FrameLayout.LayoutParams.

在此处输入图像描述

在此处输入图像描述


推荐阅读