Why do we need to use Context.obtainStyledAttributes and declare-styleable to get the attribute of the GUI component

I just came across an example tutorial code that uses declare-styleable in XML and Context.obtainStyledAttributes in Java code.

I understand that it is trying to get the attribute (as the background color) of the GUI component.

I was wondering why should we go through these cumbersome steps to get a simple attribute? If I want to retrieve the attributes of the GUI component each time, I need to create a new XML file and add the attribute that I want to get in the XML file itself. Can we make something simpler?

Right now, this is what I need to do when I try to get a GUI component attribute.


http://developer.android.com/resources/tutorials/views/hello-gallery.html

Create an XML file.

 <?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="HelloGallery"> <attr name="android:galleryItemBackground" /> </declare-styleable> </resources> 

Have the following Java code.

 TypedArray a = context.obtainStyledAttributes(R.styleable.HelloGallery); mGalleryItemBackground = a.getResourceId( R.styleable.HelloGallery_android_galleryItemBackground, 0); a.recycle(); 

We have something simple, for example

 helloGalleryInstance.getBackground(); 

As with Swing, here is what I usually do to get the attribute of a GUI component. It is fun and easy. Can we do something like this in Android?

 instaceOfAComponent.getBackground(); 
+4
source share
2 answers

In fact, it is much more. The technique of using styles and getting attributes is a way to allow consumers of a custom component to use the XML attributes that you define for the control. For example, you can create a TitleWithSubtitle control that has a subtitle text size attribute. This method will allow you to get the value from the XML layout. You can still add the getSubtitleTextSize () method to the control itself, but this will serve a different purpose.

+5
source

To get the View background, call getBackground() .

0
source

Source: https://habr.com/ru/post/1341246/


All Articles