问题
I've written a subclass of EditText. Here is that subclass:
package com.package.foo;
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.EditText;
public class FuturaEditText extends EditText{
public FuturaEditText(Context context) {
this(context, null, 0);
}
public FuturaEditText(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public FuturaEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
if(!isInEditMode()) {
setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/futura.ttf"));
}
}
}
yet it doesn't behave like an EditText, but a TextView. In particular, the soft keyboard isn't rising on focus and it has no EditText formatting. Why?
回答1:
For completeness - from the source:
public EditText(Context context, AttributeSet attrs) {
this(context, attrs, com.android.internal.R.attr.editTextStyle);
}
So, if the constructor is called with no default style, it defaults to editTextStyle
回答2:
This implementation, with each constructor calling the matched super constructor:
package com.package.foo;
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.EditText;
public class FuturaEditText extends EditText{
public FuturaEditText(Context context) {
super(context);
if(!isInEditMode()) {
setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/futura.ttf"));
}
}
public FuturaEditText(Context context, AttributeSet attrs) {
super(context, attrs);
if(!isInEditMode()) {
setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/futura.ttf"));
}
}
public FuturaEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
if(!isInEditMode()) {
setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/futura.ttf"));
}
}
}
works. I can only assume that EditText(context, attrs, 0) is not the same as EditText(context, attrs).
回答3:
You should not invoke the super constructor completing the missing arguments, otherwise there's no way for a client to invoke a constructor with less than 3 arguments (i.e. super.(Context context, AttributeSet attrs)).
The second version is the correct one.
来源:https://stackoverflow.com/questions/16040376/subclass-of-edittext-isnt-behaving-like-edittext