Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get AttributeSet properties

Tags:

Suppose i have a class which extends ViewGroup

public class MapView extends ViewGroup 

It is included in the layout map_controls.xml like this

<com.xxx.map.MapView     android:id="@+id/map"     android:background="@drawable/address"     android:layout_width="fill_parent"     android:layout_height="fill_parent"> </com.xxx.map.MapView> 

How do i retrieve properties in the constructor from AttributeSet ? Let's say the drawable in the background field.

public MapView(Context context, AttributeSet attrs) { } 
like image 974
Raymond Chenon Avatar asked Nov 07 '11 13:11

Raymond Chenon


People also ask

What is AttributeSet Android?

AttributeSet (Android Docs)A collection of attributes, as found associated with a tag in an XML document.

How to create Custom Attribute in Android?

First you must declare a namespace to find your attributes. You do this on the root layout element. Normally there is only xmlns:android="http://schemas.android.com/apk/res/android" . You must now also add xmlns:whatever="http://schemas.android.com/apk/res-auto" .

What is attribute set?

Attribute sets can be defined as a list of attributes where all the characteristics of a product are demonstrated. For a new product the attribute set works as a template. Every product must belong to a specific attribute set which comes helpful in cases of: Dividing the products into groups.


1 Answers

In the general case, you do like this:

public MapView(Context context, AttributeSet attrs) {     // ...      int[] attrsArray = new int[] {         android.R.attr.id, // 0         android.R.attr.background, // 1         android.R.attr.layout_width, // 2         android.R.attr.layout_height // 3     };     TypedArray ta = context.obtainStyledAttributes(attrs, attrsArray);     int id = ta.getResourceId(0 /* index of attribute in attrsArray */, View.NO_ID);     Drawable background = ta.getDrawable(1);     int layout_width = ta. getLayoutDimension(2, ViewGroup.LayoutParams.MATCH_PARENT);     int layout_height = ta. getLayoutDimension(3, ViewGroup.LayoutParams.MATCH_PARENT);     ta.recycle(); } 

Pay attention to how the indexes of the elements in in attrsArray matter. However, in your particular case, it works just as good to use the getters, like you discovered yourself:

public MapView(Context context, AttributeSet attrs) {     super(context, attrs); // After this, use normal getters      int id = this.getId();     Drawable background = this.getBackground();     ViewGroup.LayoutParams layoutParams = this.getLayoutParams(); } 

This works because the attribute you have on com.xxx.map.MapView are basic attributes that the View base class parses in its constructor. If you want to define your own attributes, take a look at this question and the excellent answer: Declaring a custom android UI element using XML

like image 144
Martin Nordholts Avatar answered Oct 31 '22 07:10

Martin Nordholts