0

I am adding EditText dynamically on press of Add button. I have handled dynamic creation of widgets and adding them to existing xml layout. But the problem is in the text size. I am using 15 SP in xml layout and want to keep the same size for dynamically created ones also.

I have applied the following code to calculate the text size dynamically:

int txtSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 15, getResources().getDisplayMetrics());
EditText child = new EditText(MyActivity.this); 
child.setTextSize(txtSize);

Its not producing the desired results and text size varies according to different screen sizes in spite of the fact that I am using Scaled Pixels.

Please help...

RamKr
  • 756
  • 10
  • 17

3 Answers3

0

Here is one way to do it:

  1. Define alternative "style" resource for devices with different screen size.

    • Create res/values-sw480dp and res/values-sw720dp folder (assuming you need to handle screen width 480 and 720 pixels)
    • Add a styles.xml in the each resource folder with different screen size
    • styles.xml contains a style like the following:

    <style name="DetailText"> <item name="android:textColor">@color/detail_text_color</item> <item name="android:textStyle">bold</item> <item name="android:textSize">22sp</item> </style>

  2. Add logic in your code to retrieve the text size from the style file. This link shows you how to retrieve valute of attribute in style file: How to retrieve style attributes programmatically from styles.xml

Community
  • 1
  • 1
Mei-Lin
  • 286
  • 2
  • 4
  • Thanks Mei-Lin for the answer. Actually above solution worked for me. Thank you very much. – RamKr Apr 03 '14 at 17:29
0

Try:

int textSize = 15;
EditText child = new EditText(MyActivity.this); 
child.setTextSize(Android.Util.ComplexUnitType.Sp, textSize);
Ivan Verges
  • 595
  • 3
  • 10
  • 25
  • I'm working on C# and this works for me, maybe you need to change a little bit this code to work on java but should work fine. – Ivan Verges Apr 01 '14 at 16:20
  • Thanks Ivan Verges, its working, I replaced with this for Java language 'child.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15)' – RamKr Apr 03 '14 at 17:24
0

just write this code

EditText child = new EditText(MyActivity.this); 
child.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);

reference

http://developer.android.com/reference/android/util/TypedValue.html#COMPLEX_UNIT_SP

Mina Fawzy
  • 20,852
  • 17
  • 133
  • 156