2012-03-16 4 views
27

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

Успешная установка minLines, maxLines и textColor.

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

мой 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 в моем атрибуту. 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 к EditText.

+0

какую ошибку вы получаете? – Mayank

+0

Я не получил никаких ошибок.Его работа прекрасна. Я не знаю, как назначить тип ввода? вместо того, чтобы давать грубое целочисленное значение, я хочу использовать enum (android: inputtype) в android. –

ответ

0

Мне удалось сделать это с необработанным значением 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" /> может помочь, но не знаю, как использовать его.

59

Допустим, у вас есть пользовательский вид с именем 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(); 
    ... 
+0

Я знаю, что это очень старое сообщение, но мне было интересно, есть ли способ заставить eclipse отображать предложения, подобные этому для edittext? – dzsonni

+0

Мне не удалось сделать предложения по экрану eclipse. Возможно, это сработает в будущих обновлениях adt. – Alexey

+0

Работает ли этот код? Поскольку я сделал все, как написано здесь, но в моем пользовательском классе я не могу получить атрибут inputType. не может разрешить эту строку: case R.styleable.InputView_android_inputType: – Jilberta

2

используйте это в своем attr.xml для предложений. использование флагов дает предложения в xml при использовании edittext. обычай: 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>