Подтвердить что ты не робот

Использовать declare styleable для установки типа ввода пользовательских компонентов

У меня есть CompositeComponent (EditText + ImageButton) При нажатии на кнопку содержимое edittext будет очищено. Он работает нормально. Моя проблема заключается в настройке атрибутов для моего компонента. Я использую declare-styleable для установки атрибутов для моего компонента.

Мне удавалось установить minLines, maxLines и textColor.

Как я могу установить inputtype в свой компонент через xml.

my attributes.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CET">
        <attr name="MaxLines" format="integer"/>
        <attr name="MinLines" format="integer"/>
        <attr name="TextColor" format="color"/>
        <attr name="InputType" format="integer" />
        <attr name="Hint" format="string" />
    </declare-styleable>
</resources>

И использование mycomponent в main_layout.xml:

<com.test.ui.ClearableEditText
        xmlns:cet="http://schemas.android.com/apk/res/com.test.ui"
        android:id="@+id/clearableEditText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        cet:MaxLines="2"
        cet:MinLines="1"
        cet:TextColor="#0000FF"
        cet:InputType="" <---I cant set this property--------->
        cet:Hint="Clearable EditText Hint">

    </com.test.ui.ClearableEditText>

Обычное использование Edittext:

<EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="numberSigned" <--------I want to use this property--------> >

Я не могу использовать ENUM в моем attribute.xml. Как передать android:inputType="numberSigned" в мой cet:InputType?

EDIT:

Вот как я назначаю свойства в моем ClearableEditText.java

TypedArray a = getContext().obtainStyledAttributes(attrs,R.styleable.CET,0, 0);

            int minLines = a.getInt(R.styleable.CET_MinLines, 1);
            int maxLines = a.getInt(R.styleable.CET_MaxLines, 100);
            String hint = a.getString(R.styleable.CET_Hint);
            int textColor = a.getColor(R.styleable.CET_TextColor, Color.BLACK);
            int inputType = a.getInt(R.styleable.CET_InputType, -108);

            Log.i(TAG, "ClearableEditText: Min Line "+minLines +" Max Lines: "+maxLines+" Hint "+hint+" Color: "+textColor+" Input Type: "+inputType);

            edit_text.setMaxLines(maxLines);
            edit_text.setMinLines(minLines);
            edit_text.setTextColor(textColor);
            edit_text.setHint(hint);
            if(inputType != -108)
                edit_text.setInputType(inputType);

Вы можете видеть, что нет никакой проблемы с назначением свойства inputType для редактированияText.

4b9b3361

Ответ 1

Мне удалось сделать это с необработанным значением int: Я думаю, что это не очень хорошая практика. Я могу назначить необработанные значения следующим образом: cet:InputType="2"

2 для числа (для значений: http://developer.android.com/reference/android/text/InputType.html#TYPE_CLASS_NUMBER и http://developer.android.com/reference/android/R.styleable.html#TextView_inputType)

Я считаю, что <attr name="InputType" format="reference" /> может помочь, но не знает, как его использовать.

Ответ 2

Предположим, у вас есть пользовательский вид с именем InputView, который не является TextView (скажем, RelativeLayout).

В вашем attrs.xml:

<declare-styleable name="InputView">

    <!-- any custom attributes -->
    <attr name="title" format="string" /> 

    <!-- standart attributes, note android: prefix and no format attribute -->
    <attr name="android:imeOptions"/> 
    <attr name="android:inputType"/>

</declare-styleable>

В макете xml, где вы хотите включить InputView:

<!-- note xmlns:custom and com.mycompany.myapp -->
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res-auto"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

        <!-- note that you will be using android: prefix for standart attributes, and not custom: prefix -->
        <!-- also note that you can use standart values: actionNext or textEmailAddress -->
        <com.mycompany.myapp.InputView
        android:id="@+id/emailField"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        custom:title="@string/my_title"
        android:imeOptions="actionNext|flagNoExtractUi"
        android:inputType="textEmailAddress" />

</FrameLayout>

Внутри пользовательского класса вы можете извлекать атрибуты как обычно:

    ...

    private String title;
    private int inputType;
    private int imeOptions;

    ...
    TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.InputView);

    int n = a.getIndexCount();
    for (int i = 0; i < n; i++) {
        int attr = a.getIndex(i);
        switch (attr) {
        case R.styleable.InputView_title:
            title = a.getString(attr);
            break;
        //note that you are accessing standart attributes using your attrs identifier
        case R.styleable.InputView_android_inputType:
            inputType = a.getInt(attr, EditorInfo.TYPE_TEXT_VARIATION_NORMAL);
            break;
        case R.styleable.InputView_android_imeOptions:
            imeOptions = a.getInt(attr, 0);
            break;
        default:
            Log.d("TAG", "Unknown attribute for " + getClass().toString() + ": " + attr);
            break;
        }
    }

    a.recycle();
    ...

Ответ 3

используйте это в своем attr.xml для предложений. использование флагов дает предложения в xml при использовании edittext. custom: inputType = "text" и он предложит вам типы добавления. для добавления дополнительных флагов используйте эту ссылку Посетите https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/res/res/values/attrs.xml

<resources>

<declare-styleable name="ClearableEditText">
    <attr name="hintText" format="string" />
    <attr name="inputType" format="integer">

        <!-- There is no content type. The text is not editable. -->
        <flag name="none" value="0x00000000" />
        <!--
Just plain old text. Corresponds to
{@link android.text.InputType#TYPE_CLASS_TEXT} |
{@link android.text.InputType#TYPE_TEXT_VARIATION_NORMAL}.
        -->
        <flag name="text" value="0x00000001" />
        <!--
Can be combined with <var>text</var> and its variations to
request capitalization of all characters. Corresponds to
{@link android.text.InputType#TYPE_TEXT_FLAG_CAP_CHARACTERS}.
        -->
    </attr>
  </declare-styleable>

</resources>