Skip to content

Example: Using non standard measurements

woodjk edited this page Apr 20, 2012 · 2 revisions

This is a brief example aimed at anyone that may not want to use fill_parent, wrap_content or pixel count when setting a width/height for one of your views.

You will first need to import android's TypedValue class

java_import 'android.util.TypedValue'

This will have you acces to the applyDimension method, which works like so,

TypedValue.applyDimension(unit, value, metrics)

Where unit is the unit you want to convert to, value is the number of units you want, and metrics is the devices display metrics. We can accomplish this conversion like this:

px = TypedValue.applyDimension(TypedValue::COMPLEX_UNIT_SP, 20, getResources.getDisplayMetrics)

That will give you the number of pixels for that device that is the equivalent to 20sp. For a list of all of the units you are able to choose from, visit: http://developer.android.com/reference/android/util/TypedValue.html

Lets now create a simple app with an image, that has a width measured in points, inside a linear layout.

require 'ruboto/activity'
require 'ruboto/widget'

java_import 'android.util.TypedValue'

ruboto_import_widgets :LinearLayout, :ImageView

$activity.start_ruboto_activity "$sample_activity" do
  setTitle 'Some Title'

  def on_create(bundle)
    self.content_view = linear_layout do
      px = TypedValue.applyDimension(TypedValue::COMPLEX_UNIT_PT, 20,
                                     getResources.getDisplayMetrics)
      image_view(:image_resource => $package::R.drawable.logo,
                 :width => px)
    end
  end
end

And that is all there is to it.

Clone this wiki locally