简体   繁体   English

如何以编程方式设置textview的样式?

[英]How can I set a textview's style programmatically?

How can I add a style to a textview in java? 如何在Java中向textview添加样式? I am trying to add one under my values/styles.xml, not to add each attribute individually. 我试图在我的values / styles.xml下添加一个,而不是单独添加每个属性。

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

messagesLayout.addView(sentOne);

You may find this answer by Benjamin Piette handy. 您可能会方便地找到本杰明·皮耶特(Benjamin Piette)的答案 To change this into working code for a TextView just change it up a bit: 要将其更改为TextView的工作代码,只需对其进行一些更改:

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. 编辑:要设置其他内容,例如边距,高度和宽度等,请使用LayoutParams。 To set the params throrin19's answer can be helpful. 设置throrin19的答案可能会有所帮助。

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
        LinearLayout.LayoutParams.WRAP_CONTENT,      
        LinearLayout.LayoutParams.WRAP_CONTENT
);
params.setMargins(left, top, right, bottom);
tv.setLayoutParams(params);

There is an answer for this already: https://stackoverflow.com/a/7919203/5544859 对此已经有一个答案: 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 归功于:@Raz

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM