Android 附加依赖属性
我刚刚用android开发了不到两个月,我认为这是一个很棒的工具,现在我已经开始了我的项目,以扩展一些视图来添加新功能(例如:使用自定义字体),但我有一个问题,有一个WPF功能(.NET framework),在这种情况下非常有用,不需要扩展类 这称为,基本上是向现有类添加新属性的能力 普通Android示例Android 附加依赖属性,android,design-patterns,Android,Design Patterns,我刚刚用android开发了不到两个月,我认为这是一个很棒的工具,现在我已经开始了我的项目,以扩展一些视图来添加新功能(例如:使用自定义字体),但我有一个问题,有一个WPF功能(.NET framework),在这种情况下非常有用,不需要扩展类 这称为,基本上是向现有类添加新属性的能力 普通Android示例 定期添加这样的功能将不得不扩展TextView类,但使用附加属性时,我们可以做到这一点 附属性示例 这节省了大量的工作,因为我们不仅可以在TextView中使用,还可以在其他类中使
定期添加这样的功能将不得不扩展TextView类,但使用附加属性时,我们可以做到这一点
附属性示例
这节省了大量的工作,因为我们不仅可以在TextView中使用,还可以在其他类中使用对不起,但是您不能发明新的属性用于现有类,也不能使用标准的膨胀机制。首先,在
视图中没有存储该数据的位置
也就是说,没有什么可以阻止您使用第二个XML块中的语法。只是LayoutInflater
会忽略无法识别的内容(构建工具可能会抱怨)。你可以:
- 尝试将
LayoutInflater
克隆到您自己的应用程序中,并使用与自定义属性相关的附加功能对其进行增强,或者
- 将布局XML从
Resources
加载到XmlResourceParser
中,遍历它以找到所有自定义属性,并将它们应用到由常规LayoutInflater
后者虽然更麻烦,但可能更容易实现(LayoutInflater
可能在SDK之外有很多依赖项),并且应该更容易维护(LayoutInflater
可能会随着时间的推移而改变,需要重新报告)。您链接到的文档“假定您从Windows呈现基础(WPF)类上现有依赖属性的消费者的角度来理解依赖性属性,并已读取依赖性属性概述。因为WPF开发者和Android开发者之间的重叠是很小的,你可以考虑编辑你的问题来解释“附加属性”是什么。我还想到克隆LayoutInflater,但是最好想想其他的东西,因为在一个新版本的Android中,你可以失去所有的工作。
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:my="http://schemas.android.com/apk/res/com.package.custom"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<com.package.CustomTextView
android:layout_width="fill_parent"
android:text="@string/hello"
android:layout_height="wrap_content"
android:id="@+id/TextView01"
android:textColor="@colors/text_color"
my:fontface="fonts/my-custom-font.ttf"
my:autosize="true"/>
<com.package.CustomButton
android:id="@+id/btn_continue"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/text_btn"
my:fontface="fonts/my-custom-btn-font.ttf" />
</LinearLayout>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:my="http://schemas.android.com/apk/res/com.package.custom"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<!-- there is no need to extend the class -->
<TextView
android:layout_width="fill_parent"
android:text="@string/hello"
android:layout_height="wrap_content"
android:id="@+id/TextView01"
android:textColor="@colors/text_color"
my:fontface="fonts/my-custom-font.ttf"
my:autosize="true"/>
<Button
android:id="@+id/btn_continue"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/text_btn"
my:fontface="fonts/my-custom-btn-font.ttf" />
</LinearLayout>