【问题标题】:How to pass custom attributes to nested xml如何将自定义属性传递给嵌套 xml
【发布时间】:2018-11-08 01:31:16
【问题描述】:

我有这样的结构:

preferences.xml:

...

<com.example.MyCustomPreference
    ...
    myCustomMessage="@string/abc"
    android:inputType="..."
    ... />

...

preference_my_custom.xml:

<LinearLayout ...>

    <com.example.MyCustomView
        ...
        app:myCustomMessage="?????"
        ... />

</LinearLayout>

view_my_custom.xml:

<GridView ...>
    ...EditTexts, TextViews, etc.
</GridView>

我想使用 XML 将 myCustomMessage 的值(为了简化我省略了其他属性)从 MyCustomPreference 传递给 MyCustomView。 MyCustomView 读取自定义属性,所以我想避免以编程方式读取 MyCustomPreference 中的属性,从 MyCustomView 获取 TextViews 并设置它们的值。但是,我真的不知道用什么来代替“??????”。

我怎样才能使用 XML 做到这一点?这可能吗?

【问题讨论】:

  • 我看过了。我认为我的问题略有不同。我不使用 ,也不想使用对资源的引用,而是使用已经作为属性传递的值。
  • 您的问题略有不同,但据我所知,解决方案是相同的(数据绑定)
  • 乐于助人:)

标签: android android-custom-view attr


【解决方案1】:

您必须以编程方式进行(除非您使用data binding)。例如,在您的 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();
}

在这里,您获得了属性的 String 值。然后,我假设您在您的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 的其他子视图。

现在,更改preferences.xml 中的String resId,界面应该会按预期更新。

P.S:由于我不知道您所有的资源 ID,请根据您的项目调整它们。

【讨论】:

  • 感谢您的回答和准确的解释。也许没有办法像我预期的那样简单,但是这个解决方案效果很好,而且您还提到了数据绑定,所以我可以接受您的回答。
  • 很高兴听到这个消息! :)
【解决方案2】:

为你的customeView创建一个属性文件:

在 attrs.xml 中添加

<declare-styleable name="CustomView">
    <attr name="width" format="dimension" />
</declare-styleable>

在你的 customView 初始化中使用:

 public CustomView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);

    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomView, defStyle, 0);
    mWidth = a.getDimensionPixelSize(R.styleable.CustomView_width,0);
    a.recycle();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-08
    • 2021-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多