如何访问android资源属性

如何访问android资源属性,android,android-attributes,typedarray,Android,Android Attributes,Typedarray,我想访问 getContext().obtainStyledAttributes(attrs,android.R.styleable.TextView) 但是我在可设置样式的中有错误。android.R中没有可设置样式的 我将在复合视图中使用此值 public class CustomTextView extends TextView { public CustomTextView(Context context) { super(context); init(null);

我想访问

getContext().obtainStyledAttributes(attrs,android.R.styleable.TextView)


但是我在
可设置样式的
中有错误。
android.R
中没有可设置样式的

我将在复合视图中使用此值

public class CustomTextView extends TextView {
 public CustomTextView(Context context) {
    super(context);
    init(null);
 }

 public CustomTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init(attrs);
 }

 public CustomTextView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init(attrs);
 }

 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
 public CustomTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);
    init(attrs);
 }

 private void init(AttributeSet attrs) {
    if (attrs != null && !isInEditMode()) {
        TypedValue typedValue = new TypedValue();
        int[] textSizeAttr = new int[] { android.R.attr.textSize };
        int indexOfAttrTextSize = 0;
        TypedArray a = getContext().obtainStyledAttributes(typedValue.data, textSizeAttr);
        int textSize = a.getDimensionPixelSize(indexOfAttrTextSize, -1);
        a.recycle();
    }
 }
}

布局文件

您可以这样尝试:

private void init(AttributeSet attrs) {

    if (attrs != null && !isInEditMode()) {
        int[] attrsArray = new int[] {
                android.R.attr.textSize, // 0
        };
       TypedArray a = getContext().obtainStyledAttributes(attrs, attrsArray);
       int textSize = a.getDimensionPixelSize(0 /*index of attribute in attrsArray*/, View.NO_ID);
  }
}
textSize将返回像素中的值

如果您希望在sp中获得textsize的确切值,那么在自定义视图的构造函数(AttributeSet中的构造函数)中,您可以从Android的命名空间中检索属性,如下所示:

String xmlProvidedSize = attrs.getAttributeValue("http://schemas.android.com/apk/res/android", "textSize");

xmlProvidedSize的值将类似于“16.0sp”,可能只需编辑一点字符串,您就可以提取数字。

尝试清理项目并重建它,直到我无法使用
int textSize=a.getDimensionPixelSize(android.R.styleable.TextView\u textSize)我的主要动机是从中获取“textSize”属性值。@HarishGyanani:我认为它会解决您的问题。:-)我已经发布了更多的代码,请检查。我尝试过调试,但在textSize变量中得到了-1。是否要得到在XML中使用的textSize值?或者您想在运行时设置它?正如您在我的布局文件中看到的,我使用了
android:textSize=“16sp”
String xmlProvidedSize = attrs.getAttributeValue("http://schemas.android.com/apk/res/android", "textSize");