Thursday, July 23, 2015

Android: adjustViewBounds="true" doesn't work on some devices. Here's the solution.

I am so disappointed on Android platform.

       <ImageView  
         android:layout_width="match_parent"  
         android:layout_height="wrap_content"  
         android:adjustViewBounds="true"  
         android:scaleType="fitCenter"  
         android:src="@drawable/photo" />  

If you want to have an image's width matches to the screen width and have the height change dynamically. Above is how to code. (scaleType="fitXY") also works.

Not so simple!

Although the code works on the most Android devices, it doesn't work on some devices (such as Samsung S4).

Here's the solution:
       <com.example.code.KeepRatioImageView  
         android:layout_width="match_parent"  
         android:layout_height="wrap_content"  
         android:scaleType="fitCenter"  
         android:src="@drawable/photo" />  


 public class KeepRatioImageView extends ImageView {  
   public KeepRatioImageView(final Context context, final AttributeSet attrs) {  
     super(context, attrs);  
   }  
   @Override  
   protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {  
     final Drawable d = this.getDrawable();  
     if (d != null) {  
       final int width = MeasureSpec.getSize(widthMeasureSpec);  
       final int height = (int) Math.ceil(width * (float) d.getIntrinsicHeight() / d.getIntrinsicWidth());  
       this.setMeasuredDimension(width, height);  
     } else {  
       super.onMeasure(widthMeasureSpec, heightMeasureSpec);  
     }  
   }  
 }  

Tuesday, July 21, 2015

Android: Get device screen refresh rate



Typically most devices have 60fps refresh rate. (eg. Nexus 5, Samsung S5)
Here's how to find the refresh rate of a device.
 Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();  
 float refreshRating = display.getRefreshRate();