kotlin-android 自定义控件问题记录

问题一

java中自定义控件的必备构造函数三贱客(Context context, AttributeSet attrs, int defStyleAttr),具体功能不详述了,

kotlin中构造函数,举个栗子

class CircleView (context: Context, attrs: AttributeSet? = null,defStyle: Int = android.R.attr.editTextStyle) : View(context, attrs, defStyle)

系统会优先推荐这种集成好的,所以问题来了,接下来我要装个逼了,

运行后给你报个错

Caused by: android.view.InflateException: Binary XML file line #53: Binary XML file line #53: Error inflating class com.xx.xxx.lib_component.editText.CircleView
Caused by: android.view.InflateException: Binary XML file line #53: Error inflating class com.xx.xxx.lib_component.editText.CircleView
Caused by: java.lang.NoSuchMethodException: <init> [class android.content.Context, interface android.util.AttributeSet]

网上也有告诉你是少了那三贱客,所以你就懵逼了,明明给了(Context context, AttributeSet attrs, int defStyleAttr),

然后你一顿瞎操作你就会发现你需要老老实实的写三个构造

 constructor(context: Context) : this(context, null, 0)

 constructor(context: Context, attrs: AttributeSet) : this(context, attrs, 0)

 constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAtt) {
        initView(attrs,defStyleAttr)
    }

然后就木有问题了,

当然还有个骚操作,构造前加上@JvmOverloads,你就可一直这样骚

class ClearEditText @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null,
    defStyle: Int = android.R.attr.editTextStyle
) : EditText(context, attrs, defStyle), View.OnFocusChangeListener, TextWatcher {
    init {
        initView()
    }

好了,有问题在记录

优秀的分割线------------------------------------------------------------------------------

 

问题2

做了一个简单的listView适配,所以直接选择了继承BaseAdapter(),快捷实现里面的方法后,看上去一切都完美

然后给我报了个看不到的错误

java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter convertView
	at xxx.xt.tlq.com.widget.blurView.MyListAdapter.getView(Unknown Source:2)
......
......

然后我安照提示点了getView(Unknown Source:2),就尼玛给我跳到这里来了,

由于自动导入的getView是没有非空的形参

 override fun getView(position: Int, convertView: View, parent: ViewGroup): View {
        return null
    }

 然后查到是convertView的null异常,受益于只要在View后面加个"?"就好,

可参考:https://stackoverflow.com/questions/53794754/parameter-specified-as-non-null-is-null-method-kotlin-jvm-internal-intrinsics-c

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章