从资源XML文件中获取Layout.xml方向/高度/宽度属性



首先:我想做什么?答:当方向更改没有的情况下,我正在尝试进行基本的布局改组。

这是我的activity_main.xml:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/black"
    android:paddingLeft="0dp"
    android:paddingRight="0dp"
    android:paddingTop="0dp"
    android:paddingBottom="0dp"
    android:orientation="@string/wrapper_orientation"
    tools:context=".MainActivity">
    <ImageView
        android:layout_width="@string/image_width"
        android:layout_height="@string/image_height"
        android:layout_weight="@string/image_weight"
        android:background="@drawable/customborder"
        />
    <LinearLayout
        android:layout_width="@string/content_width"
        android:layout_height="@string/content_height"
        android:layout_weight="@string/content_weight"
        android:orientation="vertical">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight=".5"
            android:background="@drawable/customborder"
            />
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight=".5"
            android:background="@drawable/customborder">
        </RelativeLayout>
    </LinearLayout>
</LinearLayout>

我在/values-land和/values-port中都有一个strings.xml文件,此处是一个示例:

<resources>
    <string name="wrapper_orientation">vertical</string>
    <string name="image_width">fill_parent</string>
    <string name="image_height">0dp</string>
    <string name="image_weight">.45</string>
    <string name="content_width">fill_parent</string>
    <string name="content_height">0dp</string>
    <string name="content_weight">.55</string>
</resources>

这在模拟器中正常工作,但是当我将其发送到手机时,应用程序将通过以下错误关闭通货膨胀:

android.view.InflateException: Binary XML file line #1: Error inflating class <unknown>
Caused by: java.lang.NumberFormatException: Invalid int: "vertical"

我认为这是因为它检索资源,错误的类型正在返回。但是我不确定为什么或如何解决。两个小时的谷歌搜索并没有太大帮助。

只是另一个注意事项:如果我将方向进行垂直编码,那就失败了,说我的第一个ImageView没有Layout_width,所以我很确定我至少在正确的轨道上。

我在这里是一个简单的人,希望能够轻松完成自己的目标吗?任何帮助都赞赏。我正在使用最新的Android Studio,而我的Minsdk是14。我所有的Main .Java文件目前都是标准膨胀,此概念证明是我到目前为止所做的:

setContentView(R.layout.activity_main);

预先感谢!

pic(链接,嘘,无代表)的效果很好:

https://i.stack.imgur.com/xfmhc.png

在XML中,垂直和水平方向名称不是字符串,而是整数定义的整数常数。您正在解决此问题的错误方法。更好的选项是使用具有适当预选赛中资源目录中定义的多个布局文件。因此,您将在res中有一个layout-port和一个layout-land文件夹,其中每个方向的布局都具有相同名称的布局XML文件,每个方向的布局都有适当的更改。您可以在此处阅读有关资源预选赛的更多信息:

支持多个屏幕

最新更新