Robolectric RoboAttributeSet is never read

It seems that the RobotoAttributeSet created and passed to the user view is never read or created incorrectly.

Here is my test:

 ArrayList<Attribute> attributes = new ArrayList<>(); attributes.add( new Attribute("com.package.name:attr/CustomButton_inputType", String.valueOf(2), "com.package.name")); // no matter what value I use (2) AttributeSet attrs = new RoboAttributeSet(attributes, Robolectric.application.getResources(), CustomButton.class); CustomButton button = new CustomButton(Robolectric.application, attrs); 

Here is my attr.xml :

  <?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="CustomButton"> <attr name="inputType" format="enum"> <enum name="text" value="0"/> <enum name="textEmailAddress" value="1"/> <enum name="password" value="2"/> </attr> </declare-styleable> </resources> 

CustomButton Part:

 private void applyAttributes(Context context, AttributeSet attrs) { TypedArray typedArray = context.getTheme() .obtainStyledAttributes(attrs, R.styleable.CustomButton, 0, 0); try { int typeValue = // is always 0 typedArray.getInt(R.styleable.CustomButton_inputType, 0); switch (typeValue) { case 0: // do something break; case 1: // do something break; case 2: // do something break; default: // just do nothing break; } } finally { typedArray.recycle(); } } 

So, no matter what value I set when preparing the attributes (this is example 2 in the example), I always get 0 for typeValue .

Am I doing something wrong? Many thanks!

+5
source share
2 answers

The problem comes from your test, especially the value passed to the AttributeSet. In fact, instead of passing an enumeration value field, you should pass an enumeration name field so that you can get the bound value field last in your view.

 attributes.add( new Attribute("com.package.name:attr/CustomButton_inputType", "textEmailAddress", "com.package.name")); 

Hope this can help :) Also, feel free to refer to my post on custom attributes .

+3
source

Try

 attributes.add( new Attribute("com.package.name:attr/inputType", String.valueOf(2), "com.package.name")); 
0
source

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


All Articles