gpt4 book ai didi

android - 如何从java代码中读取自定义维度属性

转载 作者:IT老高 更新时间:2023-10-28 21:47:48 24 4
gpt4 key购买 nike

我制作了我的自定义组件,只是将几个 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 正是我想要的值。

最佳答案

有几句话要说:

  • 首先,您需要在 xml 的顶部有一个 xml namespace 声明行,与使用 android xmlns 的方式完全相同:xmlns:foo="http://schemas.android.com/apk/res-自动”
  • 那么你需要在 valueTextSize 前面加上你的 xmlns : foo:valueTextSize="40sp"

之后,获取字符串不是一个好主意,android提供了更强大的解决方案来处理维度:

int unitsTextSize = typedArray.getDimensionPixelSize(R.styleable.BasicGauge_unitsTextSize, textSize);

还有一些微妙之处:

  • 对于 Paint 或 TextPaint,您可以按原样使用此值:paint.setTextSize(unitTextSize):
  • 对于 TextView ,上述方法会失败,您必须使用 setText 的重载才能获得正确的结果:textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, unitTextSize);

区别在于所谓的“原始像素”(根据密度未缩放,只是原始)和“缩放像素”(相反)。

关于android - 如何从java代码中读取自定义维度属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16596980/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com