作者热门文章
- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我制作了我的自定义组件,只是将几个 TextView 放在一起。现在我希望能够直接从代码初始化我的自定义控件,为每个电视独立传递文本大小
我的属性定义:
<resources>
<declare-styleable name="BasicGauge">
<attr name="valueTextSize" format="dimension" />
<attr name="titleTextSize" format="dimension" />
<attr name="unitsTextSize" format="dimension" />
</declare-styleable>
</resources>
组件初始化示例:
<pl.com.digita.BikeComputerUi.customviews.BasicGauge
android:id="@+id/basicGauge1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:padding="10dp"
valueTextSize="40sp">
</pl.com.digita.BikeComputerUi.customviews.BasicGauge>
我如何尝试在组件的构造函数中读取这些属性:
final int N = typedArray.getIndexCount();
for (int i = 0; i < N; i++) {
int attribute = typedArray.getIndex(i);
switch (attribute) {
case R.styleable.BasicGauge_valueTextSize:
valueTextSize = typedArray.getString(attribute);
break;
case R.styleable.BasicGauge_titleTextSize:
titleTextSize = typedArray.getString(attribute);
break;
case R.styleable.BasicGauge_unitsTextSize:
unitsTextSize = typedArray.getString(attribute);
break;
}
typedArray.recycle();
}
问题:创建后,我的所有值仍然为空。 40sp 正是我想要的值。
最佳答案
有几句话要说:
之后,获取字符串不是一个好主意,android提供了更强大的解决方案来处理维度:
int unitsTextSize = typedArray.getDimensionPixelSize(R.styleable.BasicGauge_unitsTextSize, textSize);
还有一些微妙之处:
paint.setTextSize(unitTextSize):
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, unitTextSize);
区别在于所谓的“原始像素”(根据密度未缩放,只是原始)和“缩放像素”(相反)。
关于android - 如何从java代码中读取自定义维度属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16596980/
我是一名优秀的程序员,十分优秀!