是的,有可能
让我们假设你的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文件(在值目录下)声明属性名称,以便在何时可以使用自定义视图,从这些属性收集的值将被交给您的构造函数。
所以,让我们看看你如何声明这些自定义属性,就像你问过的那样:
这是我的整个attrs.xml
现在您可以在XML中设置TextViews的大小,但不能在Layout中声明命名空间,下面是如何:
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属性集中的第一行。
我希望这有助于乔希,