2013-09-08 5 views
4

Я пытаюсь сделать пользовательский вид и объявили стилизованных атрибуты, как внизу: -Настройка цвета объекта Paint в настраиваемое представление

<resources> 
<declare-styleable name="NewCircleView"> 
    <attr name="radius" format="integer"/> 
    <attr name="circlecolor" format="color"/> 
</declare-styleable> 

</resources> 

в конструкторе customview, эти значения получаются как ниже: -

circleradius=a.getInt(R.styleable.NewCircleView_radius, 0);//global var 
    circlecolor=a.getColor(R.styleable.NewCircleView_circlecolor, 0);//global var and a is the typed array 

мнение используется объявлении XML, как показано ниже: -

<com.customviews.NewCircleView 
     android:layout_below="@id/thetext" 
     android:layout_width="match_parent" 
     android:layout_height="fill_parent" 
     app:radius="10000" 
     app:circlecolor="@color/black"<!--this is defined in colors.xml 
     /> 

В настраиваемое представление, когда я установить объект краски, как: -

thePaintObj.setColor(circlecolor);//circlecolor logs to an integer as expected 

Я не получаю цвето- «черный» определяется в XML

однако, когда я установить цвет как

thePaintObj.setColor(Color.GRAY) 

Получу цвет на вид

Может кто-нибудь сказать мне, что я буду делать неправильно?

(N.B: -Если вы хотите, чтобы я размещать больше кода, пожалуйста, дайте мне знать)

EDIT1: - Проводка моего colors.xml. Похоже, что не ясно, в моих комментариях к коду: -

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
<color name="red">#7f00</color> 
<color name="blue">#770000ff</color> 
<color name="green">#7700ff00</color> 
<color name="yellow">#77ffff00</color> 
<color name="black">#000000</color> 
</resources> 
+0

Необходимо указать цвета в цветах.xml – Raghunandan

ответ

10

В colors.xml

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <color name="black_color">#000000</color> 
</resources> 

Чтобы получить

Resources res = getResources(); 
int color = res.getColor(R.color.black_color); 

Затем установите цвет покрасить

thePaintObj.setColor(color); 

Дополнительная информация @

http://developer.android.com/guide/topics/resources/more-resources.html#Color

Edit:

MyCustomView

public class CustomView extends View{ 

    Paint p; 
    int color ; 
    public CustomView(Context context) { 
     this(context, null); 
    } 

    public CustomView(Context context, AttributeSet attrs) { 
     this(context, attrs, 0); 
    } 

    public CustomView(Context context, AttributeSet attrs, int defStyle) { 
     super(context, attrs, defStyle); 
     // real work here 
     TypedArray a = context.getTheme().obtainStyledAttributes(
       attrs, 
       R.styleable.NewCircleView, 
       0, 0 
     ); 

     try { 

     color = a.getColor(R.styleable.NewCircleView_circlecolor, 0xff000000); 
     } finally { 
      // release the TypedArray so that it can be reused. 
      a.recycle(); 
     } 
     init(); 
    } 

public void init() 
{ 
     p = new Paint(); 
     p.setColor(color); 
} 

    @Override 
    protected void onDraw(Canvas canvas) { 
     // TODO Auto-generated method stub 
     super.onDraw(canvas); 
     if(canvas!=null) 
     { 
     canvas.drawCircle(100, 100,30,p); 
     } 
    } 

} 

attrs.xml

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <declare-styleable name="NewCircleView"> 
    <attr name="radius" format="integer"/> 
    <attr name="circlecolor" format="color" /> 
</declare-styleable> 
</resources> 

colors.xml

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <color name="black_color">#000000</color> 
</resources> 

MyCustomView в XML

<com.example.circleview.CustomView 
     xmlns:android="http://schemas.android.com/apk/res/android" 
     xmlns:app="http://schemas.android.com/apk/res/com.example.circleview" 
     android:id="@+id/cv" 
     android:layout_width="match_parent" 
     android:layout_height="fill_parent" 
     app:radius="30" 
     app:circlecolor="@color/black_color" 
     /> 

Snap Shot

enter image description here

+0

Я уже указал цвета в colors.xml, как указано в моих комментариях к коду, и я получаю его через xml, где пользовательское представление используется как приложение: circlecolor = "@ цвет/черный ", который, как я полагаю, такой же, как и выше. Пожалуйста, дайте мне знать, если я ошибаюсь – Rasmus

+0

@itamecodes действительно проверяют это http://stackoverflow.com/questions/3441396/defining-custom-attrs – Raghunandan

+0

@itamecodes я просто попробовал, и он работает для меня. Я отправлю то же самое. – Raghunandan

0

Если я правильно понимаю, постоянные 0x000000 результатов в прозрачном черном, так как нет компонента Альфа указано. Значение Alpha - это первый байт четырехзначного значения цвета.Константа для непрозрачного (сплошного) черного равна 0xff000000. Другими словами, цвет 0x000000, который совпадает с 0x00000000, приводит к тому, что вы рисуете полностью прозрачно. Константа для Red также выглядит неправильно, в результате чего прозрачный зеленый цвет.

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