我想访问
getContext().obtainStyledAttributes(attrs,android.R.styleable.TextView)
但我在styleable
中遇到错误。 styleable
中没有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();
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="hgyanani.customcompoundview.MainActivity">
<hgyanani.customcompoundview.CustomTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textSize="16sp" />
</RelativeLayout>
答案 0 :(得分:2)
您可以尝试这样:
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的值将是这样的&#34; 16.0sp&#34;也许只需要一点字符串编辑就可以提取数字。