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);

2 Answers 2

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);
2
  • I've looked at that answer. The issue I have with it is that it does not copy over layou_margin, layout weight, and layout_height among others. I've defined all those in styles Jun 6, 2017 at 18:49
  • You can (should) define those in LayoutParams Jun 6, 2017 at 18:50
-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

1
  • Sorry, but that answer is for textstyle (bold, italic, normal). I am asking about style (all other attributes). Jun 6, 2017 at 18:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.