微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Android获取膨胀的layout layout_width和layout_height值

Android中,如何获取在XML文件中设置的值?

my_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="300dp"
    android:layout_height="500dp"
    android:orientation="vertical" >
    .....
<RelativeLayout/>

我已经尝试了以下方法,但均未成功:

View v = ((LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
            R.layout.my_layout, null);

//this gave me -1(LayoutParams.FILL_PARENT), which is not what I want. I need 300
v.getLayoutParams().width
// same for height, it gives me -1
 v.getLayoutParams().width

我不在乎视图的实际外观,我只需要这些值…

我知道在完成测量后就可以获取视图的宽度和高度(onGlobalLayout),但这不是我所需要的.我需要的是XML中的值.

EDIT1:我知道v.getWidth()和v.getHeight()在视图显示在屏幕上后可以工作,在测量发生之前它们将无法工作

解决方法:

如果您要解析XML布局以获取一些属性,请尝试以下操作:

 Resources r = getResources();
    XmlResourceParser parser = r.getLayout(R.layout.your_layout);

    int state = 0;
    do {
        try {
            state = parser.next();
        } catch (XmlPullParserException e1) {
            e1.printstacktrace();
        } catch (IOException e1) {
            e1.printstacktrace();
        }       
        if (state == XmlPullParser.START_TAG) {
            //here get the attributes you want..., with AttributeSet for example
            }
        }
    } while(state != XmlPullParser.END_DOCUMENT);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐