Android custom attributes not showing

I have seen a lot of posts with people wanting to know how to get custom attributes for a custom component, but that is not my question. I created a custom component and I try to add attributes, but when I add a namespace at the top of my xml file, it finds only two random user attributes: paddingEnd and paddingStart.

<resources> <declare-styleable name="menu_item_attrs"> <attr name="imageId" format="integer" /> <attr name="menuText" format="string" /> </declare-styleable> </resources> 

This is attrs.xml file.

 public MenuListItem(Context context, AttributeSet set) { super(context, set); TypedArray a = context.obtainStyledAttributes(set, R.styleable.menu_item_attrs); if (a == null) { return; } CharSequence s = a.getString(R.styleable.menu_item_attrs_menuText); if (s != null) { // do something } } 

This is the constructor in my custom class.

  <LinearLayout xmlns:custom="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="0dp" android:id="@+id/expanding_layout" android:background="#029eed"> <aaron.testappanim.MenuListItem android:layout_height="wrap_content" android:layout_width="wrap_content"/> </LinearLayout> 

This is my component to use. I want to add values ​​to "imageId" and "menuText", but they are not available. The only thing that is displayed is the add-on, as shown below.

enter image description here

Any ideas guys?

+5
source share
2 answers

Found a solution.

As it happens, you must have a style name, the same as the name of your class.

 <resources> <declare-styleable name="MenuListItem"> <attr name="my_custom_attribute" format="integer" /> </declare-styleable> </resources> 

In this case, many posts on this topic are wrong, as I see a lot when the style names are completely different.

Hope this can prevent someone else from falling into this trap.

Greetings

+12
source

My solution was: In the attr.xml file, you can specify your own attribute as follows

<declare-styleable name="IDEditText"> <attr name="customFont" format="string"/> </declare-styleable>

Here, the declare-styleable name declare-styleable should be the name of the custom view. Then it will be shown in the sentences.

In my case, my user name is of the form IDEditText , so declare-styleable name = "IDEditText"

-1
source

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


All Articles