2013-04-14 4 views
0

Я пытаюсь создать пользовательские атрибуты xml, которые могут быть приняты больше классов, чем один. Я нашел (среди прочих) этот полезный ответ: Defining custom attrsКак получить доступ к стандартным атрибутам xml?

Но как получить доступ к атрибуту программно? Eclipse, как представляется, не найти определенные имена:

Вот мой attrs.xml, это «ViewPadding я пытаюсь использовать:

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
<attr name="ViewPadding" format="integer"/> 
<declare-styleable name="IntegerPicker"> 
    <attr name="maxNrOfDigits" format="integer"/> 
    <attr name="NumberSize" format="integer"/> 
    <attr name="ViewColor" format="color"/> 
    <attr name="TextAlignRight" format="boolean"/> 
</declare-styleable> 

<declare-styleable name="DoublePicker"> 
    <attr name="CompoundViewColor" format="color"/> 
    <attr name="CompoundViewPadding" format="integer"/> 
</declare-styleable> 
</resources> 

Это код, я использую, чтобы получить доступ к другим атрибутам:

public IntegerPicker(Context context, AttributeSet attrs) { 
    super(context, attrs); 

    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    inflater.inflate(R.layout.integer_picker, this, true); 

    etInteger = (EditText) findViewById(R.id.etInteger); 

    TypedArray a = context.obtainStyledAttributes(attrs, 
      R.styleable.IntegerPicker); 

     final int N = a.getIndexCount(); 
     for (int i = 0; i < N; ++i) 
     { 
      int attr = a.getIndex(i); 
      switch (attr) 
      { 
      case R.styleable.IntegerPicker_ViewColor: 
       int ViewColor = a.getColor(attr, 0); 
       this.setBackgroundColor(ViewColor); 
       break; 
      case R.styleable.IntegerPicker_maxNrOfDigits: 
       int ems = a.getInteger(attr, 8); 
       etInteger.setEms(ems); 
       break; 
      case R.styleable.: 
       int padding = a.getInteger(attr, 10); 
       etInteger.setPadding(padding, padding, padding, padding); 
       break; 
      case R.styleable.IntegerPicker_NumberSize: 
       int NumberSize = a.getInteger(attr, 10); 
       etInteger.setTextSize(NumberSize); 
       break; 
      case R.styleable.IntegerPicker_TextAlignRight: 
       boolean textAlignRight = a.getBoolean(attr,false); 
       if(textAlignRight){ 
        etInteger.setGravity(0x05); 
       }else{ 
        etInteger.setGravity(0x03); 
       } 
      } 
     } 
     a.recycle(); 

} 

Как обрабатывать:

LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    inflater.inflate(R.layout.integer_picker, this, true); 

и

case R.styleable.IntegerPicker_ViewColor: 
       int ViewColor = a.getColor(attr, 0); 
       this.setBackgroundColor(ViewColor); 

Пожалуйста, помогите, я действительно в убыток здесь: S

ответ

0

Я не специалист в этом, но вы можете захотеть попробовать это: (Взято из SlidingMenu)

AttrS .xml

<!-- 
    Copyright 2011 The Android Open Source Project 

    Licensed under the Apache License, Version 2.0 (the "License"); 
    you may not use this file except in compliance with the License. 
    You may obtain a copy of the License at 

     http://www.apache.org/licenses/LICENSE-2.0 

    Unless required by applicable law or agreed to in writing, software 
    distributed under the License is distributed on an "AS IS" BASIS, 
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
    See the License for the specific language governing permissions and 
    limitations under the License. 
--> 

<resources> 

    <declare-styleable name="SlidingMenu"> 
     <attr name="mode"> 
      <enum name="left" value="0" /> 
      <enum name="right" value="1" /> 
     </attr> 
     <attr name="viewAbove" format="reference" /> 
     <attr name="viewBehind" format="reference" /> 
     <attr name="behindOffset" format="dimension" /> 
     <attr name="behindWidth" format="dimension" /> 
     <attr name="behindScrollScale" format="float" /> 
     <attr name="touchModeAbove"> 
      <enum name="margin" value="0" /> 
      <enum name="fullscreen" value="1" /> 
     </attr> 
     <attr name="touchModeBehind"> 
      <enum name="margin" value="0" /> 
      <enum name="fullscreen" value="1" /> 
     </attr> 
     <attr name="shadowDrawable" format="reference" /> 
     <attr name="shadowWidth" format="dimension" /> 
     <attr name="fadeEnabled" format="boolean" /> 
     <attr name="fadeDegree" format="float" /> 
     <attr name="selectorEnabled" format="boolean" /> 
     <attr name="selectorDrawable" format="reference" /> 
    </declare-styleable> 

</resources> 

код, чтобы получить атрибут XML (в представлении конструктора)

// get all attributes 
    final TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.SlidingMenu); 
    // extract 1 attribute, of return SlidingMenu.LEFT if no attr was supplied) 
    final int mode = ta.getInt(R.styleable.SlidingMenu_mode, SlidingMenu.LEFT); 
+0

Прошу прощения, если я пропустил его, но эти атрибуты работают только с классом SlidningMenu. Я хочу использовать атрибуты с несколькими классами. Как это (по ссылке выше) Вы можете определить атрибуты в верхнем элементе или внутри элемента . Если я собираюсь использовать attr в более чем одном месте, я помещаю его в корневой элемент. Обратите внимание: все атрибуты имеют одно и то же глобальное пространство имен. Моя проблема в том, что я не знаю, как ее адресовать после того, как я объявил attrs – SverkerSbrg

+0

Я думаю, что они не привязаны к классу. Вы должны иметь доступ к своим значениям attrs через окончательный TypedArray ta = context.obtainStyledAttributes (attrs, R.styleable.IntegerPicker); и ta.getInt (R.styleable.IntegerPicker_maxNrOfDigits, -1) –

+0

Да, те, которые привязаны к классу i, могут получить доступ, но не к свободным. К тому же основная проблема в том, что я пропустил, поняла, что это имя в объявлении-стиле. – SverkerSbrg

Смежные вопросы