attrs.xml中android:gravity的正确格式? [英] Correct format for android:gravity in attrs.xml?

查看:382
本文介绍了attrs.xml中android:gravity的正确格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情况:

styles.xml中:

<style name="fooStyle">
    <item name="android:padding">?fooView.padding</item>
    <item name="android:background">?fooView.background</item>
    <item name="android:gravity">?fooView.gravity</item>
</style>

attrs.xml中:

<attr name="fooView.padding" format="dimension" />
<attr name="fooView.background" format="color|reference" />
<attr name="fooView.gravity" format="????"/>

themes.xml中:

<style name="fooViewTheme" parent="android:Theme">
    <item name="fooView.padding" >2dip</item>
    <item name="fooView.background" >#AA000000</item>
    <item name="fooView.gravity">right|bottom</item>
</style>

问题是我无法弄清楚fooView.gravity的格式是什么.我已经尝试过stringenumflag,但是似乎都没有用:只要加载了使用该主题的视图,我总是会得到一个java.lang.NumberFormatException: unable to parse 'right|bottom' as integer.

The problem is that I cannot figure out what the format for the fooView.gravity should be. I've already tried with string, enum and flag but none seem to work: I always get a java.lang.NumberFormatException: unable to parse 'right|bottom' as integer as soon as the view that uses this theme gets loaded.

感谢所有答案.

推荐答案

这些是Android使用的重力值.您可以在attrs.xml中使用它:

Those are the gravity values used by Android. You can use that in your attrs.xml:

<resources>
    <declare-styleable name="MyCustomView">
        <attr name="gravity">
            <flag name="bottom" value="80" />
            <flag name="center" value="17" />
            <flag name="center_horizontal" value="1" />
            <flag name="center_vertical" value="16" />
            <flag name="clip_horizontal" value="8" />
            <flag name="clip_vertical" value="128" />
            <flag name="end" value="8388613" />
            <flag name="fill" value="119" />
            <flag name="fill_horizontal" value="7" />
            <flag name="fill_vertical" value="112" />
            <flag name="left" value="3" />
            <flag name="right" value="5" />
            <flag name="start" value="8388611" />
            <flag name="top" value="48" />
        </attr>
    </declare-styleable>
</resources>

在布局XML中,您可以通过以下方式使用它:

In your layout XML you can use it this way:

<MyCustomView
        custom:gravity="center|bottom"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

在Java代码中,您可以使用以下代码读取值:

And in Java code you can read the value using this:

int gravity = a.getInt(R.styleable.MyCustomView_gravity, Gravity.NO_GRAVITY);

并直接将其设置为子视图(如果您认为合适的话):

and directly set it to a sub view, if that makes sense for you:

someSubView.setGravity(gravity);

您可以在android.view.Gravity这里

这篇关于attrs.xml中android:gravity的正确格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆