Android 如何将自定义属性传递给嵌套的xml
我有这样的结构: preferences.xml:Android 如何将自定义属性传递给嵌套的xml,android,android-custom-view,attr,Android,Android Custom View,Attr,我有这样的结构: preferences.xml: ... <com.example.MyCustomPreference ... myCustomMessage="@string/abc" android:inputType="..." ... /> ... 。。。 ... 首选项\u my\u custom.xml: <LinearLayout ...> <com.example.MyCustomView
...
<com.example.MyCustomPreference
...
myCustomMessage="@string/abc"
android:inputType="..."
... />
...
。。。
...
首选项\u my\u custom.xml:
<LinearLayout ...>
<com.example.MyCustomView
...
app:myCustomMessage="?????"
... />
</LinearLayout>
<GridView ...>
...EditTexts, TextViews, etc.
</GridView>
查看\u my\u custom.xml:
<LinearLayout ...>
<com.example.MyCustomView
...
app:myCustomMessage="?????"
... />
</LinearLayout>
<GridView ...>
...EditTexts, TextViews, etc.
</GridView>
…编辑文本、文本视图等。
我想使用XML将myCustomMessage的值(为了简化,我省略了其他属性)从MyCustomPreference传递到MyCustomView。MyCustomView读取自定义属性,因此我希望避免以编程方式读取MyCustomPreference中的属性,从MyCustomView获取文本视图并将其设置为值。然而,我真的不知道用什么来代替“??”的输入
如何使用XML实现这一点?这是可能的吗?您必须以编程方式进行操作(除非您使用
数据绑定
)。例如,在您的MyCustomPreference
中,捕获de属性myCustomMessage
:
String myCustomMessage = null;
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyCustomPreference, 0, 0);
try {
myCustomMessage = a.getString(R.styleable.MyCustomPreference_myCustomMessage);
} finally {
a.recycle();
}
这里是属性的字符串
值。然后,我猜您已经在您的MyCustomPreference
中膨胀了MyCustomView
。例如:
View.inflate(getContext(), R.layout.preference_my_custom, this);
MyCustomView myCustomView = (MyCustomView) findViewById(R.id.you_custom_view_id);
因此,您可以在MyCustomView
中以编程方式设置myCustomMessage
myCustomView.setMyCustomMessage(myCustomMessage);
您应该创建此方法以正确设置文本,并在必要时将此文本传播到MyCustomView
的其他子视图
myCustomView.setMyCustomMessage(myCustomMessage);
现在,更改首选项.xml中的字符串
resId时,界面应按预期更新
注意:由于我不知道您的所有资源ID,请根据您的项目调整它们。为您的customeView创建一个属性文件:
加载项attrs.xml
<declare-styleable name="CustomView">
<attr name="width" format="dimension" />
</declare-styleable>
可能是我见过的那个的复制品。我想我的问题略有不同。我不使用,也不想使用对资源的引用,而是使用已作为属性传递的值。您的问题稍有不同,但据我所知,解决方案是相同的(数据绑定)。感谢您指出它。乐于帮助:)感谢您的回答和准确解释。也许没有办法像我期望的那样简单,但是这个解决方案非常有效,而且您也提到了数据绑定,所以我可以接受您的答案。很高兴听到这个消息!:)