Custom EditText - Material Design

2019-08-13 22:02发布

问题:

I developed an own class, which extends EditText. But my custom view has an other look as the normal view.

public class DateEditText extends EditText {
    [...]

    public DateEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public DateEditText(Context context) {
        super(context);
        init();
    }

    public DateEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        setInputType(InputType.TYPE_CLASS_DATETIME);
        setFilters(new InputFilter[]{new InputFilter.LengthFilter(10)});
        setFocusable(false);
    }

    [...]
}

The first two input fields are normal EditText's. The third is my own view.

    <EditText
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:id="@+id/addTask_title"
        android:textSize="16sp"
        android:maxLength="50"
        android:hint="@string/addTask_title"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="56dp"
        android:maxLines="5"
        android:scrollbars="vertical"
        android:inputType="textMultiLine"
        android:id="@+id/addTask_description"
        android:textSize="16sp"
        android:maxLength="400"
        android:hint="@string/addTask_description"/>

    <de.test.DateEditText
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:id="@+id/addTask_date"
        android:textSize="16sp"
        android:hint="@string/addTask_date"/>

I like to have the same style for my own EditText as the first two, but I don't know how to realize this.

On devices with SDK 21 all is okay, but below SDK 21 the third view looks differently.

回答1:

Add style="@style/Widget.AppCompat.EditText" in your custom EditText.

Eg:

<de.test.DateEditText
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:id="@+id/addTask_date"
        android:textSize="16sp"
        android:hint="@string/addTask_date"
        style="@style/Widget.AppCompat.EditText"/>


回答2:

For applying colorAccent just extend your custom EditText class from android.support.v7.widget.AppCompatEditText