Search code examples
androidandroid-layoutandroid-edittext

View extending EditText loses Styles and is not focusable


I try to subclass EditText for convenience reasons (NumberEdit) using kotlin but the rendered View loses most of the EditText properties. The look is that of a TextView and it is not focusable with the mouse (in the emulator). When I click into the activity I can then edit the first of the NumberEdit widgets and can cycle to the next one with the tab key.

I added two emulator screenshots to illustrate the difference.

An EditText looks like this

An EditText looks like this

The new NumberEdit looks like this

The new NumberEdit looks like this

The extended class looks like this:

import android.content.Context
import android.text.InputType
import android.util.AttributeSet
import android.widget.EditText


class EditNumber(context: Context, attributeSet: AttributeSet?, defStyleAttr: Int, defStyleRes: Int)
    : EditText(context, attributeSet, defStyleAttr, defStyleRes) {

    constructor(context: Context) : this(context, null, 0, 0)
    constructor(context: Context, attributeSet: AttributeSet?) : this(context, attributeSet, 0, 0)
    constructor(context: Context, attributeSet: AttributeSet?, defStyleAttr: Int)
        : this(context, attributeSet, defStyleAttr, 0)

    init {
        inputType = InputType.TYPE_CLASS_NUMBER + InputType.TYPE_NUMBER_FLAG_DECIMAL
    }
}

Does anyone have a clue what I am doing wrong? Do I have to reference some attributes explicitly?


Solution

  • I'm not a kotlin expert but if you look at the java source code for edittext you have following:

    public class EditText extends TextView {
        public EditText(Context context) {
            this(context, null);
        }
        public EditText(Context context, AttributeSet attrs) {
            this(context, attrs, com.android.internal.R.attr.editTextStyle);
        }
        public EditText(Context context, AttributeSet attrs, int defStyleAttr) {
            this(context, attrs, defStyleAttr, 0);
        }
        public EditText(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
            super(context, attrs, defStyleAttr, defStyleRes);
        }
    

    It doesn't look like you pass the right parameters to the constructor... You pass a lot of 0s and nulls...