简体   繁体   English

您可以在 XML 布局文件中将视图设置为另一个视图的属性吗?

[英]Can you set a view as a property of another view in an XML layout file?

We have a custom GridView which has headerView and footerView properties.我们有一个自定义的GridView ,它具有headerViewfooterView属性。 I'm wondering if in Android, it's possible to set those properties from within a layout file.我想知道在 Android 中是否可以从布局文件中设置这些属性。

XAML in Windows lets you do this easily since you can specify properties either via attributes (for things like strings, numbers or other simple types), or via nested elements (for any object type) with a ControlType:PropertyName syntax. Windows 中的 XAML 使您可以轻松完成此操作,因为您可以通过属性(对于字符串、数字或其他简单类型等)或通过具有ControlType:PropertyName语法的嵌套元素(对于任何对象类型)来指定ControlType:PropertyName

Here's a pseudo-version of what this would look like if Android supported something similar:如果 Android 支持类似的东西,这是一个伪版本:

<MyCustomGrid
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <!-- This would set the 'headerView' property
         on 'MyCustomGrid' to a TextView -->
    <MyCustomGrid:headerView>

        <TextView android:text="I'm the Header TextView" />

    </MyCustomGrid:headerView>

</MyCustomGrid>

Obviously the above is not valid.显然,以上是无效的。 But is it possible to do something similar in Android, or do I have to do it in the code-behind in the Activity/Fragment?但是有可能在 Android 中做类似的事情,还是我必须在 Activity/Fragment 的代码隐藏中做?

Yes, you can.是的你可以。

You can create a Custom View by extending the GridView class and add some logic through attributes.您可以通过扩展 GridView 类并通过属性添加一些逻辑来创建自定义视图 This will not work as an attached property from XAML (Like Grid.Column or Grid.Row from XAML UWP) but you can do something like this:这不能作为 XAML 的附加属性(如 XAML UWP 的 Grid.Column 或 Grid.Row),但您可以执行以下操作:

<com.teste.widget.MarqueIVGridView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:my_header="@layout/my_header"
/>

Don't forget to add the namespace at the root of your layout:不要忘记在布局的根目录添加命名空间:

xmlns:app="http://schemas.android.com/apk/res-auto"

Google has this sample: HeaderGridView谷歌有这个示例: HeaderGridView

It uses a different approach, if you copy this class you will just need to use this "HeaderGridView" and call addHeaderView method from it sending your header view inflated.它使用不同的方法,如果你复制这个类,你只需要使用这个“HeaderGridView”并从它调用 addHeaderView 方法发送你的标题视图。

Feel free to ask any question and It will be a pleasure to answer.随时提出任何问题,很高兴回答。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM