Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Robolectric's RoboAttributeSet is never read

Looks like RobotoAttributeSet created and passed to a custom view is never read or constructed 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>

A part of CustomButton:

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 attributes (it is 2 in the example), I always get 0 for typeValue.

Am I doing something wrong? Thanks a lot!

like image 212
Eugene Avatar asked Oct 20 '22 19:10

Eugene


1 Answers

The issue comes from your test, especially the value passed to the AttributeSet. Indeed, instead of passing the value field of the enum, you should pass the name field of the enum, so you can, latter on your view, get the associated value field.

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

Hope this could help :) Also, do not hesitate to go and look at my post dealing with custom attributes.

like image 73
Turhan Oz Avatar answered Oct 22 '22 10:10

Turhan Oz