【发布时间】:2019-07-01 17:54:31
【问题描述】:
我正在尝试将这段代码从 Java 翻译成 Kotlin。但是,我正在努力处理接收整数作为参数的第二个构造函数的“超级”调用。
package info.androidhive.volleyexamples.volley.utils;
import com.android.volley.toolbox.ImageLoader.ImageCache;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
public class LruBitmapCache extends LruCache<String, Bitmap> implements
ImageCache {
public static int getDefaultLruCacheSize() {
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
return cacheSize;
}
public LruBitmapCache() {
this(getDefaultLruCacheSize());
}
public LruBitmapCache(int sizeInKiloBytes) {
super(sizeInKiloBytes);
}
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight() / 1024;
}
@Override
public Bitmap getBitmap(String url) {
return get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
put(url, bitmap);
}
}
到目前为止,我已经做到了。如您所见,LruCache 要求您将某些内容作为参数传递。但我想用“getDefaultLruCacheSize”方法计算这个参数。
class LruBitmapCache(var maxSize: Int = 0) : LruCache<String, Bitmap>(maxSize), ImageCache {
private fun getDefaultLruCacheSize(): Int {
val maxMemory = (Runtime.getRuntime().maxMemory() / 1024).toInt()
return maxMemory / 8
}
init {
maxSize = getDefaultLruCacheSize()
}
override fun sizeOf(key: String?, value: Bitmap?): Int = if (value != null) {
(value.rowBytes * value.height / 1024)
} else{
val defaultValue = 1
defaultValue
}
override fun getBitmap(url: String?): Bitmap? = get(url)
override fun putBitmap(url: String?, bitmap: Bitmap?) {
put(url, bitmap)
}
问题是我目前的方法是在我的 init 方法之前调用 super。
【问题讨论】:
-
在android studio中,如果它在一个.kt文件里面,它不会把它改成kotlin吗?
-
@soldfor 我不知道我是否用得不好,但它并没有像我预期的那样工作。另外,我正在尝试学习 Kotlin,所以手动编写会很有用。
-
@Leonardo Rocha。考虑处理您的 Java 代码库并将其粘贴到 Android Studio 中,您应该可以选择将代码库转换为 kotlin。
标签: android inheritance kotlin