android - 是否可以获取 android layout.xml 文件中声明的小部件的属性值?

标签 android android-layout android-widget android-resources android-databinding

在 android 应用程序中是否有一种方法可以检索在 layout.xml 中声明的小部件的属性值?

例如在我的 layout.xml 文件中我有:

<CheckBox
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:text="@string/clean_filesWithoutVideo"
     android:checked="@{uiprefs.switchButtonEditable}"
     android:id="@+id/checkbox_updateable" />

我想检索 android:checkedliteral 值,例如我想检索 "@{uiprefs.switchButtonEditable}"在运行时。

我在 android.content.res.Resources 类中使用 getResources() 从 Activity 中搜索但没有成功:

  • 我无法将 xml 文件作为流获取。
  • 通过 Resources.getLayout() 解析属性不会恢复属性值。

也许这个值隐藏在 CheckBox 实例中的某处,但我无法在调试时使用检查找到它...

注意:我要检索的值尤其是数据绑定(bind)文字。也许我可以通过数据绑定(bind) API 检索它?

最佳答案

每个 UI 组件都有自己的 getter 和 setter,通过它们您可以检索当前设置的属性或设置您想要的属性。如果属性在 View 中是通用的,例如高度/宽度,则 getter 将在 View 类中可用。
在您的情况下,您可以通过以下方式获取 checked 属性:

CheckBox checkbox =  (CheckBox) view.findViewById(R.id.checkbox_updateable);
boolean initialState = checkbox.isChecked();

在 Android Studio 中,您可以获得可用于特定 View 的方法。输入 var 名称(比如复选框)然后输入点 (.),它会显示所有可用的方法。开始输入您认为正在寻找的内容,它会向您显示所有相关方法。

更新

我认为AttributeSet是你要找的。你可以这样做:

 XmlPullParser parser = resources.getXml(myResource);
 AttributeSet attributes = Xml.asAttributeSet(parser);

来自文档:

The implementation returned here, unlike using the implementation on top of a generic XmlPullParser, is highly optimized by retrieving pre-computed information that was generated by aapt when compiling your resources. For example, the getAttributeFloatValue(int, float) method returns a floating point number previous stored in the compiled resource instead of parsing at runtime the string originally in the XML file.

This interface also provides additional information contained in the compiled XML resource that is not available in a normal XML file, such as getAttributeNameResource(int) which returns the resource identifier associated with a particular XML attribute name.

关于android - 是否可以获取 android layout.xml 文件中声明的小部件的属性值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33996481/

相关文章:

java - 必须释放分数忍者才能保存分数吗?

java - 二进制 XML 文件行 #15 : Failed to resolve attribute at index 1: TypedValue{t=0x2/d=0x7f030003 a=-1}

java.lang.ClassCastException : android. widget.LinearLayout 无法转换为 android.support.v7.widget.Toolbar

java - java.lang.Package.getDeclaredAnnotations 上 UnsatisfiedLinkError 的极其简化的测试用例

android - FrameLayout 的子边距底部不起作用

安卓工作室错误 : static interface method invocations are not supported in -source 1. 7

android - 是否可以在 android 相对布局的宽度上均匀分布按钮

android - 如何在 staticlayout 和 surfaceview 中包含可点击的文本

Android XML 属性引用了另一个相同类型的 xml 属性

android - 如何对齐 ActionBar 中的菜单项