是的,这是可能的;
假设您的 RelativeLayout 声明(在 xml 中)具有使用 14sp 定义的 textSize:
android:textSize="14sp"
在自定义视图的构造函数中(接受 AttributeSet 的构造函数),您可以从 Android 的命名空间中检索属性,如下所示:
String xmlProvidedSize = attrs.getAttributeValue("http://schemas.android.com/apk/res/android", "textSize");
xmlProvidedSize 的值将类似于“14.0sp”,也许只需稍加编辑字符串,您就可以提取数字。
另一种声明您自己的属性集的选项会有点冗长,但它也是可能的。
所以,你有你的自定义视图和你的 TextViews 声明了这样的权利:
public class MyCustomView extends RelativeLayout{
private TextView myTextView1;
private TextView myTextView2;
// rest of your class here
太好了……
现在您还需要确保您的自定义视图覆盖了接受 AttributeSet 的构造函数,如下所示:
public MyCustomView(Context context, AttributeSet attrs){
super(context, attrs);
init(attrs, context); //nice, clean method to instantiate your TextViews//
}
好的,现在让我们看看 init() 方法:
private void init(AttributeSet attrs, Context context){
// do your other View related stuff here //
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.MyCustomView);
int xmlProvidedText1Size = a.int(R.styleable.MyCustomView_text1Size);
int xmlProvidedText2Size = a.int(R.styleable.MyCustomView_text2Size);
myTextView1.setTextSize(xmlProvidedText1Size);
myTextView2.setTextSize(xmlProvidedText2Size);
// and other stuff here //
}
您可能想知道 R.styleable.MyCustomView、R.styleable.MyCustomView_text1Size 和 R.styleable.MyCustomView_text2Size 是从哪里来的;请允许我详细说明。
您必须在 attrs.xml 文件(在 values 目录下)中声明属性名称,以便无论您在何处使用自定义视图,从这些属性收集的值都将传递给您的构造函数。
那么让我们看看您是如何按照您的要求声明这些自定义属性的:
这是我的整个 attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyCustomView">
<attr name="text1Size" format="integer"/>
<attr name="text2Size" format="integer"/>
</declare-styleable>
</resources>
现在您可以在 XML 中设置 TextView 的大小,但不能在布局中声明命名空间,方法如下:
<com.my.app.package.MyCustomView
xmlns:josh="http://schemas.android.com/apk/res-auto"
android:id="@+id/my_custom_view_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
josh:text1Size="15"
josh:text2Size="30"
/>
请注意我如何将命名空间声明为“josh”作为您的 CustomView 属性集中的第一行。
我希望这可以帮助乔希,