Camera学习笔记(一):camera_preferences.xml分析

前端之家收集整理的这篇文章主要介绍了Camera学习笔记(一):camera_preferences.xml分析前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

原生的Camera的设置里面有很多的选项,那么首先来看一下这些选项的布局文件camera_preferences.xml。截取一段该文件如下:

  1. <PreferenceGroup
  2. xmlns:camera="http://schemas.android.com/apk/res/com.android.gallery3d"
  3. camera:title="@string/pref_camera_settings_category">
  4. <IconListPreference
  5. camera:key="pref_camera_flashmode_key"
  6. camera:defaultValue="@string/pref_camera_flashmode_default"
  7. camera:title="@string/pref_camera_flashmode_title"
  8. camera:icons="@array/camera_flashmode_icons"
  9. camera:entries="@array/pref_camera_flashmode_entries"
  10. camera:entryValues="@array/pref_camera_flashmode_entryvalues" />

上面的代码属性PreferencesGroup、IconListPreferences属于自定义属性强调一下,IconListPreferences每个属性的前面的关键字“camrea”是根据代码第二行的xmlns:camera来的。平时我们用的属性前面关键字都是“android”,你会发现xmlns后面就是就是“android”。

这些自定义属性是在文件夹 res/values/attrs.xml文件里定义的,代码如下:

  1. <resources>
  2. <declare-styleable name="CameraPreference">
  3. <attr name="title" format="string" />
  4. </declare-styleable>
  5. <declare-styleable name="ListPreference">
  6. <attr name="key" format="string" />
  7. <attr name="defaultValue" format="string|reference" />
  8. <attr name="entryValues" format="reference" />
  9. <attr name="entries" format="reference" />
  10. </declare-styleable>
  11. <declare-styleable name="IconIndicator">
  12. <attr name="icons" format="reference" />
  13. <attr name="modes" format="reference" />
  14. </declare-styleable>
  15. <declare-styleable name="IconListPreference">
  16. <!-- If a preference does not have individual icons for each entry,it can has a single icon to represent it. -->
  17. <attr name="singleIcon" format="reference" />
  18. <attr name="icons" />
  19. <attr name="largeIcons" format="reference" />
  20. <attr name="images" format="reference" />
  21. </declare-styleable>
  22. <declare-styleable name="MaxLinearLayout">
  23. <attr name="maxHeight" format="dimension" />
  24. <attr name="maxWidth" format="dimension" />
  25. </declare-styleable>
  26. </resources>

比如CameraPreference它有一个属性(name)title,该属性的格式(format)是string型。那么我们是怎么通过Java代码获取这些xml的值得呢?还是以CamerePreferences为例,在CameraPreference.xml中的构造函数有一段代码如下:

  1. public CameraPreference(Context context,AttributeSet attrs) {
  2. mContext = context;
  3. TypedArray a = context.obtainStyledAttributes(
  4. attrs,R.styleable.CameraPreference,0);
  5. mTitle = a.getString(R.styleable.CameraPreference_title);
  6. a.recycle();
  7. }

上面的几步即可完成对自定义属性的使用。

猜你在找的XML相关文章