gpt4 book ai didi

java - 访问自定义组件的 AttributeSet 中的属性

转载 作者:IT老高 更新时间:2023-10-28 20:48:42 24 4
gpt4 key购买 nike

我有一个自定义组件,其中包含两个具有自定义大小设置方法的 TextView(两个 TextView 的比例约为 1:2)。由于这是 RelativeLayout 的子类,它没有 textSize 属性,但我想知道是否仍然可以在该组件的 XML 实例化中设置 android:textSize 属性,然后从 AttributeSet 中获取 textSize 属性,以便在构造函数中与我的自定义 setSize() 方法一起使用。

我已经看到了使用自定义属性执行此操作的技术,但是如果我想获取一个已经在 android 词典中的属性怎么办?

最佳答案

是的,这是可能的;

假设您的 RelativeLayout 声明(在 xml 中)具有使用 14sp 定义的 textSize:

android:textSize="14sp"

在自定义 View 的构造函数中(接受 AttributeSet 的构造函数),您可以从 Android 的命名空间中检索属性,如下所示:

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

xmlProvidedSize 的值将类似于“14.0sp”,也许只需稍加编辑字符串,您就可以提取数字。


另一种声明您自己的属性集的选项会有点冗长,但它也是可能的。

所以,你有你的自定义 View 和你的 TextViews 声明了这样的权利:

public class MyCustomView extends RelativeLayout{

private TextView myTextView1;
private TextView myTextView2;

// rest of your class here

太好了……

现在您还需要确保您的自定义 View 覆盖了接受 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 目录下)中声明属性名称,以便无论您在何处使用自定义 View ,从这些属性收集的值都将传递给您的构造函数。

那么让我们看看您是如何按照您的要求声明这些自定义属性的:这是我的整个 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 属性集中的第一行。

我希望这可以帮助乔希,

关于java - 访问自定义组件的 AttributeSet 中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8302229/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com