【问题标题】:How to read android default attributes of a View in java code如何在java代码中读取视图的android默认属性
【发布时间】:2015-02-11 07:29:15
【问题描述】:

我想要一个名为 MyTextView 的自定义 TextView,并且我想在它的构造函数中设置一个默认 TextSize,前提是它的 XML 定义中没有设置 TextSize。如何检测是否在其 XML 定义中设置了 TextSize?

public class MyTextView extends TextView{    
    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        //How can i read TextSize from AttribureSet??
        //if no TextSize has been set then SetTextSize(defaultTextSize);
    } 
}

谁能帮帮我?

【问题讨论】:

标签: java android xml


【解决方案1】:

可以获取样式属性,如

public class MyTextView extends TextView{    
    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
         String size = attrs.getAttributeValue("http://schemas.android.com/apk/res/android", "textSize");
    } 
}

【讨论】:

  • 谢谢,这将准确返回在 xml 定义中设置的字符串,如“12.0sp”或 null 或类似的东西。谢谢你:)
【解决方案2】:

这是一个例子:

final Resources.Theme theme = context.getTheme();
TypedArray array = theme.obtainStyledAttributes(attrs, R.styleable.YourStylable, R.attr.YourDefStyleAttr, 0);

【讨论】:

  • 这仅在设置了自定义属性时才有效。不是默认值。
  • 谢谢,但我现在想谈谈默认属性而不是自定义属性。
【解决方案3】:

试试这个float size = new TextView(this).getTextSize();

【讨论】:

  • 我认为这会返回 textSize 并且无法识别它是默认 textSize 还是已在 xml 布局文件中设置。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-30
  • 1970-01-01
  • 2011-08-23
  • 1970-01-01
相关资源
最近更新 更多