【发布时间】:2010-05-13 00:51:27
【问题描述】:
我一直在尝试使用本教程在 android 中创建自定义按钮 - http://www.gersic.com/blog.php?id=56
它运行良好,但没有说明如何更改字体大小或粗细。有什么想法吗?
这里还有另一个问题,唯一的答案是使用 html 样式,但如果不使用 css(或已弃用的字体标签),您将无法更改 html 中的字体大小。必须有更好的方法来设置按钮上使用的字体的像素大小?
【问题讨论】:
标签: android
我一直在尝试使用本教程在 android 中创建自定义按钮 - http://www.gersic.com/blog.php?id=56
它运行良好,但没有说明如何更改字体大小或粗细。有什么想法吗?
这里还有另一个问题,唯一的答案是使用 html 样式,但如果不使用 css(或已弃用的字体标签),您将无法更改 html 中的字体大小。必须有更好的方法来设置按钮上使用的字体的像素大小?
【问题讨论】:
标签: android
您可以像定义其他任何东西一样在 xml 中定义这些属性,例如:
<Button android:id="@+id/next_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/next"
android:background="@drawable/mybutton_background"
android:textSize="10sp" /> <!-- Use SP(Scale Independent Pixel) -->
您可以在api 中找到允许的属性。
或者,如果您希望将其应用于应用程序中的所有按钮,请创建一个样式。请参阅Styles and Themes 开发文档。
【讨论】:
Button butt= new Button(_context);
butt.setTextAppearance(_context, R.style.ButtonFontStyle);
在 res/values/style.xml 中
<resources>
<style name="ButtonFontStyle">
<item name="android:textSize">12sp</item>
</style>
</resources>
【讨论】:
以编程方式:
Button bt = new Button(this);
bt.setTextSize(12);
在xml中:
<Button
android:textSize="10sp"
/>
【讨论】:
我试图将字体大小放在styles.xml中,但是当我去使用它时,它只允许来自dimen文件夹的资源,所以把它放在那里,不知道这是对的
<Button
android:layout_weight="1"
android:id="@+id/three_btn"
android:layout_height="match_parent"
android:layout_width="0dp"
android:onClick="onButtonClick"
android:textColor="#EEEEEE"
android:textStyle="bold"
android:textSize="@dimen/buttonFontSize"
android:text="3"/>
【讨论】:
另一种方法:
首先使用默认字体大小声明一个 int
int txtSize = 16;
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mTextView.setTextSize(txtSize++);
}
});
【讨论】:
另一种程序化方法;
final Button btn = (Button) findViewById(R.id.btnSize);
final float[] size = {12};
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
size[0] +=2;
btn.setTextSize(size[0] +2);
}
});
每次单击按钮时,按钮文本都会发生变化(+2px 大小)。您也可以添加另一个按钮并更改大小 -2px。如果您想为其他开口节省尺寸,您可以使用Shared Preference界面。
【讨论】:
<resource>
<style name="button">
<item name="android:textSize">15dp</item>
</style>
<resource>
【讨论】:
在XML文件中,ant文本包括button、textView、editText等的字体大小可以通过添加来改变
android:textSize="10sp"
【讨论】: