Reputation: 177
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);
Upvotes: 0
Views: 1372
Reputation: 389
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);
Upvotes: 4
Reputation: 2789
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
Upvotes: -1