簡體   English   中英

從資源XML文件獲取layout.xml方向/高度/寬度屬性

[英]Getting layout.xml orientation/height/width properties from resource XML file

第一:我想做什么? 答:我嘗試在方向更改時進行基本的布局改組, 而不使用自己的任何.java代碼。

這是我的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。這時我主要的.java文件都是標准的inflate,到目前為止,我一直在嘗試這一概念證明:

setContentView(R.layout.activity_main);

提前致謝!

模擬器的Pic(鏈接,噓聲,無代表)工作正常:

http://i.imgur.com/1cCJsYR.png

在xml中,垂直和水平方向名稱不是字符串,而是預定義的整數常量。 您正在使用不正確的方法來解決此問題。 更好的選擇是使用帶有適當限定符的資源目錄中定義的多個布局文件。 因此,您將在res有一個layout-portlayout-land文件夾,其中每個布局xml文件都用相同的名稱定義,並對每個方向的布局進行了適當的更改。 您可以在此處閱讀有關資源限定符的更多信息:

支持多屏

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM