attribute java 从_java – 在AttributeSet中访问自定义组件的attrs

是的,有可能

让我们假设你的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属性集中的第一行。

我希望这有助于乔希,

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值