2013-07-15 72 views
1

我想要獲得我的RelativeLayout的尺寸。在R.id中沒有RelativeLayout ID獲取RelativeLayout的尺寸

我許多告知使用如下代碼:

RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.myRelativeLayout); 
    int layoutWidth = relativeLayout.getWidth(); 
    int layoutHeight = relativeLayout.getHeight(); 

我的問題是,所有的ID我可以找到我R.id都是按鈕,文本的意見,以及所有這類。根本沒有佈局ID!

然後我試着寫:

relativeLayout = (RelativeLayout) findViewById(R.layout.main_activity); 

relativeLayout爲空時運行。所以這也是不正確的。

是否需要手動添加布局ID到R.id?我不這麼認爲。

但爲什麼在R.id中沒有編號的編號?

+0

http://stackoverflow.com/questions/7899806/get-layout-from-view可能對你有幫助 – 2013-07-15 03:10:39

+2

活動XML例如在RelativeLayout中的main.xml放置一個像這樣的id android:id =「@ + id/ui_main_holder_relative」 – Arslan

+0

你可以粘貼包含你的'RelativeLayout'的佈局xml嗎? – Geobits

回答

3

這取決於你的意思是什麼佈局。默認情況下,當您創建活動或XML佈局時,它將以R.layout.xxx存儲。但是讓我們說,在一個佈局中,你有另一個佈局(在這種情況下是嵌套佈局),你必須手動「標識」你想要引用的佈局。

例如:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context=".MainActivity" > 

    <RelativeLayout 
     android:id="@+id/CallMe" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentTop="true" 
     android:layout_marginLeft="139dp" 
     android:layout_marginTop="130dp" > 
    </RelativeLayout> 

    <RelativeLayout 
     android:layout_width="@+layout/test" 
     android:layout_height="wrap_content" 
     android:layout_alignLeft="@+id/CallMe" 
     android:layout_below="@+id/CallMe" 
     android:layout_marginTop="64dp" > 
    </RelativeLayout> 

</RelativeLayout> 

然後,您可以參考由R.id.CallMe第一相對佈局和R.layout.test

第二個

你可以使用任何名字,它不必是佈局或ID。 希望可以幫助

+0

如果它能正常工作,您能將它標記爲可接受的答案嗎?謝謝 – Riandy

+0

我當然會,當我確定它的作品。謝謝! :) –