Skip to content

Instantly share code, notes, and snippets.

@gadmyth
Created September 29, 2014 18:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gadmyth/a12baab57e0f2f2e332a to your computer and use it in GitHub Desktop.
Save gadmyth/a12baab57e0f2f2e332a to your computer and use it in GitHub Desktop.
android set text size in code
public class TestActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.i("TestActivity", "onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
TextView view = (TextView) findViewById(R.id.test_size);
int size = getResources().getDimensionPixelSize(R.dimen.test_text_size);
size = px2sp(getApplicationContext(), size);
view.setTextSize(size);
}
public static int px2sp(Context context, float pxValue) {
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (pxValue / fontScale + 0.5f);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment