Android scaling text and images based on screen size (phone vs tablet)

I have a good understanding of the difference between px, dp and sp. The problem is, when I put the TextView (or ImageView) on the screen, the dpi doesn't matter. On a 3-inch high 160dpi screen, 80px font size will be 1/2 inch, or 1/6 of the height. On a 7-inch high 160dpi screen, it's still 1/2 inch, but now it's 1/14 of the height.

The problem is using dp (or sp), what looks good on the phone disappears on the tablet.

Is there a way to specify the size of the fractional screen, like a percentage?

+3


source to share


2 answers


I'm not sure if you can specify the size as a percentage, but why don't you define different screen sizes in the dimen.xml file. It is very difficult to use the same dp and sp values ​​for all screen sizes.

You need to create different folders with different dimens.xml folders

 res/values-ldpi/dimens.xml
 res/values-mdpi/dimens.xml
 res/values-hdpi/dimens.xml

      

Then add some values ​​to these files

 <!-- in values-ldpi/dimens.xml -->
 <dimen name="textSize">25dip</dimen>

 <!-- in values-mdpi/dimens.xml -->
 <dimen name="textSize">20dip</dimen>

      



The final reference for dimensions in your layout file:

<TextView
    android:layout_toRightOf="@id/at"
    android:layout_below="@id/hw"
    android:textSize="@dimen/textSize"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

      

EDIT:

If you want to set the height of the image to 1/10 of the screen size, you need to use the android: layout_weight attribute on the view containers. Check out the example below.

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:layout_weight="1"
        >

        <ImageView
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:id="@+id/imageView"
            android:background="@drawable/ic_launcher" />
    </LinearLayout>

        <LinearLayout
            android:layout_height="wrap_content"
            android:layout_width="fill_parent"
            android:weightSum="1"
            android:layout_weight="9"
            >
 </LinearLayout>

 </LinearLayout>

      

+1


source


This will give textSize depending on the density.

  TextView text = new TextView(this);
  text.setText("text");
  TextView.setTextSize(16 * getResources().getDisplayMetrics().density);

      

OR

Create dimens.xml with values ​​-ldpi, mdpi and hdpi.



<dimen name="textSize">30dip</dimen>
<dimen name="textSize">10dip</dimen>

      

and then add this to your layout.

<TextView
android:textSize="@dimen/textSize"
    //rest code here
/>

      

+1


source







All Articles