如何获得RelativeLayout的宽度和高度

时间:2016-05-26 13:45:14

标签: android-layout

我无法获得RelativeLayout的宽度和高度,我怎么能得到它?我的layout.xml文件是

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

<RelativeLayout
    android:id="@+id/layoutMain"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_margin="50dp" >

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerInParent="true"
        android:layout_gravity="center_horizontal"
        android:src="@drawable/ic_launcher" />
</RelativeLayout>

我只是使用其内置的提供方法获得RelativeLayout的编程高度和宽度,例如,

public class CustomShowcaseActivity extends Activity {    static float width;
  static float height;  RelativeLayout relMain;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_custom_showcase);

    relMain= (RelativeLayout) findViewById(R.id.layoutMain);


    width = relMain.getMeasuredWidth();
      height = relMain.getMeasuredHeight();

    width = relMain.getWidth();
    height = relMain.getHeight();

    System.out.println("=== Width : " + width);
    System.out.println("=== height : " + height);

} } 

任何人都可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:3)

  首先

override这个方法。

@Override
    public void onWindowFocusChanged(boolean hasFocus) {
        // TODO Auto-generated method stub
        super.onWindowFocusChanged(hasFocus);
        getRelativeLayoutInfo();
    }
  

请仅使用getHeight()getWidth()

 private void getRelativeLayoutInfo(){
    relMain = (RelativeLayout) findViewById(R.id.layoutMain);
    w = relMain.getWidth();
    h = relMain.getHeight();
    Log.v("W-H", w+"-"+h);
 }