[英]How to override method in library?
那是我的帶庫的 gradle
api 'com.simplify:ink:1.0.2'
在庫文件中,只讀Inkview.java
這個方法被觸發,每次彈出時,都會顯示 showkeyboard。
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
clear();
}
我想重寫它以不調用此方法,或者在需要時調用它。 我創建了InkView.kt
fun InkView.onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
}
但無論如何它都是默認觸發的。 如何正確應用這個?
編輯:在第一篇文章之后,我創建了新的 class MyInkView 並將其添加到.xml
文件中。
<com.myApplication.fragment.extensions.MyInkView
android:id="@+id/inkView"
android:layout_margin="@dimen/padding"
android:layout_width="match_parent"
android:layout_height="match_parent" />
進入片段時出錯:
Error inflating class com.myApplication.fragment.extensions.MyInkView
Caused by: java.lang.NoSuchMethodException: com.myApplication.fragment.extensions.MyInkView.<init> [class android.content.Context, interface android.util.AttributeSet]
如果我將attributeSet
添加為 null 那么錯誤是:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.isRecycled()' on a null object reference
第二次編輯:
class MyInkView: InkView {
constructor(context: Context, attrs: AttributeSet): super(context, attrs)
constructor(context: Context): super(context)
// include any other constructors you need based on the ones in the superclass
fun InkView.onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
// your code here
}
}
不會覆蓋任何東西,也不會崩潰。 它像以前一樣工作。
class MyInkView: InkView {
constructor(context: Context, attrs: AttributeSet): super(context, attrs)
constructor(context: Context): super(context)
// include any other constructors you need based on the ones in the superclass
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
// your code here
}
}
錯誤日志:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.isRecycled()' on a null object reference
來自inkView的清除方法
// clean up existing bitmap
if (bitmap != null) {
bitmap.recycle()
}
// init bitmap cache
this.bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
canvas = Canvas(bitmap)
// notify listeners
for (listener in listeners) {
listener.onInkClear()
}
invalidate()
isEmpty = true
}
Kotlin 擴展函數是靜態解析的,不能覆蓋成員函數。
如果要覆蓋 InkView 的成員InkView
,則需要創建一個從其擴展的新 class 。
例如:
class MyInkView(context: Context): InkView(context) {
override fun InkView.onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
// your code here
}
}
要允許 Android 正確實例化 class,您可能還需要額外的兩個參數構造函數:
class MyInkView: InkView {
constructor(context: Context, attrs: AttributeSet): super(context, attrs)
constructor(context: Context): super(context)
// include any other constructors you need based on the ones in the superclass
override fun InkView.onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
// your code here
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.