3

I have my own custom component in xml written like this

    <com.app.components.CustomComponent
        android:id="@+id/component"
        android:layout_width="96dp"
        android:layout_height="96dp"
        android:scaleType="fitCenter"/>

Attrs:

<declare-styleable name="CustomComponent">
    <attr name="android:scaleType"/>
</declare-styleable>

My custom component constructor looks like this

@Bind(R.id.imageView) ImageView imageView;
@Bind(R.id.progressBar) ProgressBar progressBar;

public CustomComponent(Context context, AttributeSet attrs) {
    super(context, attrs);

    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.FunGuideImageView, 0, 0);

  // how to correctly get scale type defined in xml ?
    int scaleType = a.getValue(R.styleable.CustomComponent_android_scaleType,
            ImageView.ScaleType);


    LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.imageview, this, true);
    ButterKnife.bind(view);
    imageView.setScaleType( scaleType );

}

How can I get the scaleType defined in xml and set it to my imageView?

8
  • Shouldn't CustomComponent being extending View? Commented Mar 18, 2016 at 15:52
  • Indeed CustomComponent is extending View. How does this help ? Commented Mar 18, 2016 at 15:56
  • If you extended ImageView, you can simply do getScaleType(), otherwise, I don't think making your styleables the same names as the android: attributes is a good idea. Commented Mar 18, 2016 at 16:01
  • If I am extending ImageView I cannot inflate my custom xml anymore. So at the moment I am extending LinearLayout Commented Mar 18, 2016 at 16:03
  • Why not? As far as I can tell you are making a custom ImageView that includes a ProgessBar. Commented Mar 18, 2016 at 16:05

1 Answer 1

4

Given the first two files, You have to make the following changes in order to get it work:

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomComponent, 0, 0);
int scaleTypeIndex = a.getValue(R.styleable.CustomComponent_android_scaleType, -1);

Then you can get the ImageView.ScaleType array doing the following:

if(scaleTypeIndex > -1) {
    ImageView.ScaleType[] types = ImageView.ScaleType.values();
    ImageView.ScaleType scaleType = types[scaleTypeIndex];
    imageView.setScaleType(scaleType);
}

Remember to trash the TypedArray after use.

Sign up to request clarification or add additional context in comments.

1 Comment

I had to use val scaleType: Int = a.getInt(R.styleable. CustomComponent_android_scaleType, -1) ... a.getValue returns a Boolean ... but it works with a.getInt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.