0

How can I add a style to a textview in java? I am trying to add one under my values/styles.xml, not to add each attribute individually.

LinearLayout messagesLayout = (LinearLayout) findViewById(R.id.messages_layout);
TextView sentOne = new TextView(this);
sentOne.setText(sentMessage);

messagesLayout.addView(sentOne);
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Ethan Watson
  • 177
  • 1
  • 1
  • 8

2 Answers2

4

You may find this answer by Benjamin Piette handy. To change this into working code for a TextView just change it up a bit:

TextView tv = new TextView (new ContextThemeWrapper(this, R.style.mystyle), null, 0);

EDIT: to set other things like margins, height & width and others, use LayoutParams. To set the params throrin19's answer can be helpful.

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
        LinearLayout.LayoutParams.WRAP_CONTENT,      
        LinearLayout.LayoutParams.WRAP_CONTENT
);
params.setMargins(left, top, right, bottom);
tv.setLayoutParams(params);
user2988879
  • 379
  • 2
  • 6
  • 18
-1

There is an answer for this already: https://stackoverflow.com/a/7919203/5544859

textview.setTypeface(Typeface.DEFAULT_BOLD);

to preserve the previously set typeface attributes you can use:

textview.setTypeface(textview.getTypeface(), Typeface.DEFAULT_BOLD);

Credit to: @Raz

Red M
  • 2,609
  • 3
  • 30
  • 50