获取Android中布局的宽度/高度

时间:2022-06-14 21:20:14

I'm wondering how to measure the dimensions of a view. In my case it is aan Absolute Layout. I've read the answers concerning those questions but I still don't get it. I'm fairly new to programming so maybe it's just me. ;)

我想知道如何测量视图的尺寸。在我看来,这是一个绝对的布局。我已经读了有关这些问题的答案,但我还是不明白。我对编程相当陌生,所以可能只有我自己。,)

This is my code:

这是我的代码:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main);      

    AbsoluteLayout layoutbase = (AbsoluteLayout) findViewById(R.id.layoutbase);       

    drawOval(); 

}
public void drawOval(){ //, int screenWidth, int screenHeight){ 
    AbsoluteLayout layoutbase = (AbsoluteLayout) findViewById(R.id.layoutbase);     

    int screenWidth = layoutbase.getWidth();
    int screenHeight = layoutbase.getHeight();
    Log.i("MyActivity", "screenWidth: " + screenWidth + ", screenHeight: " +screenHeight);

    Coordinates c = new Coordinates(BUTTONSIZE,screenWidth,screenHeight);

    ...some code ...

    ((ViewGroup) layoutbase ).addView(mybutton, new AbsoluteLayout.LayoutParams(BUTTONSIZE, BUTTONSIZE, c.mX, c.mY));


    mybutton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            showText(mybutton);
        }
    });
}

public void showText(View button){      

    int x = findViewById(LAYOUT).getWidth();
    int y = findViewById(LAYOUT).getHeight(); 

    Toast message = Toast.makeText(this, "x: " + x , Toast.LENGTH_SHORT);       
    message.show();     


}

The getWidth() command works great in showText() but it does not in drawOval(). I know it looks a bit different there but I also used the int x = findViewById(LAYOUT).getWidth(); version in drawOval(), and x/y are always 0. I don't really understand why there seems to be no width/height at that earlier point. Even if I actually draw a Button on the Absolute Layout, getWidth() returns 0. Oviously I want to measure the sizes in drawOval().

getWidth()命令在showText()中很有用,但在drawOval()中不行。我知道这里看起来有点不同但我也用了int x = findViewById(布局).getWidth()在drawOval()中,x/y总是0。我真的不明白为什么前面的点没有宽度/高度。即使我在绝对布局上画了一个按钮,getWidth()也返回0。显然,我想度量drawOval()中的大小。

I would appreciate any help.

我希望得到任何帮助。

Thanks!

谢谢!

6 个解决方案

#1


10  

I think will help you.

我想这会对你有帮助。

   LinearLayout headerLayout = (LinearLayout)findviewbyid(R.id.headerLayout);
    ViewTreeObserver observer = headerLayout .getViewTreeObserver();
            observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {
            // TODO Auto-generated method stub
            int headerLayoutHeight= headerLayout.getHeight();
        int headerLayoutWidth = headerLayout.getWidth();
        headerLayout .getViewTreeObserver().removeGlobalOnLayoutListener(
                this);
    }
});


}  

#2


7  

getWidth() is giving you 0 because onCreate is called before layout actually happens. Due to views being able to have dynamic positions and sizes based on attributes or other elements (fill_parent for example) there's not a fixed size for any given view or layout. At runtime there is a point in time (actually it can happen repeatedly depending on many factors) where everything is actually measured and laid out. If you really need the height and width, you'll have to get them later as you've discovered.

getWidth()给你0,因为在布局实际发生之前,onCreate被调用。由于视图能够基于属性或其他元素(例如fill_parent)具有动态位置和大小,所以对于任何给定的视图或布局都没有固定的大小。在运行时,会有一个时间点(实际上,它可以根据许多因素反复发生),在这个时间点上,所有的东西都被实际测量和布置。如果你真的需要高度和宽度,你将不得不在你发现之后得到它们。

#3


3  

This specially deal with Dimensions so

这是专门处理维数的。

Display display = getWindowManager().getDefaultDisplay(); 
int width = display.getWidth(); 
int height = display.getHeight();

This may help you in managing dimensions.

这可能有助于您管理维度。

Note: This returns the display dimensions in pixels - as expected. But the getWidth() and getHeight() methods are deprecated. Instead you can use:

注意:这将返回以像素为单位的显示尺寸——如预期的那样。但是不赞成使用getWidth()和getHeight()方法。相反,您可以使用:

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;

as also Martin Koubek suggested.

正如马丁•库贝克(Martin Koubek)所建议的那样。

#4


2  

If your goal is to simply draw an oval on the screen, then consider creating your own custom View rather than messing around with AbsoluteLayout. Your custom View must override onDraw(android.graphics.Canvas), which will be called when the view should render its content.

如果你的目标只是在屏幕上画一个椭圆,那么考虑创建你自己的自定义视图,而不是搞得一团糟。您的自定义视图必须覆盖onDraw(android.graphics.Canvas),当视图呈现内容时将调用它。

Here is some extremely simple sample code that might help get you started:

下面是一些非常简单的示例代码,可以帮助您入门:

public class MainActivity extends Activity {

    private final Paint mPaint = new Paint();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new SampleView(this));
    }

    // create a nested custom view class that can draw an oval. if the
    // "SampleView" is not specific to the Activity, put the class in 
    // a new file called "SampleView.java" and make the class public 
    // and non-static so that other Activities can use it. 
    private static class SampleView extends View {
        public SampleView(Context context) {
            super(context);
            setFocusable(true);
        }

        @Override
        protected void onDraw(Canvas canvas) {
            canvas.drawColor(Color.CYAN);

            // smoothen edges
            mPaint.setAntiAlias(true);
            mPaint.setColor(Color.RED);
            mPaint.setStyle(Paint.Style.STROKE); 
            mPaint.setStrokeWidth(4.5f);

            // set alpha value (opacity)
            mPaint.setAlpha(0x80);

            // draw oval on canvas
            canvas.drawOval(new RectF(50, 50, 20, 40), mPaint);
        }
    }
}

#5


2  

This give you screen resolution:

这给你屏幕分辨率:

 WindowManager wm = (WindowManager)context.getSystemService(context.WINDOW_SERVICE);
 Display display = wm.getDefaultDisplay();
 Point outSize = new Point();
 display.getSize(outSize);

#6


1  

kabuko's answer is correct, but could be a little more clear, so let me clarify.

kabuko的答案是正确的,但是可能会更清楚一些,所以让我澄清一下。

getWidth() and getHeight() are (correctly) giving you 0 because they have not been drawn in the layout when you call them. try calling the two methods on the button after addView() (after the view has been drawn and is present in the layout) and see if that gives you the expected result.

getWidth()和getHeight()会(正确地)给您0,因为在调用它们时,它们并没有被绘制到布局中。尝试在addView()之后调用按钮上的这两个方法(在视图被绘制并显示在布局中之后),看看是否会得到预期的结果。

See this post for more information.

更多信息请参见本文。

#1


10  

I think will help you.

我想这会对你有帮助。

   LinearLayout headerLayout = (LinearLayout)findviewbyid(R.id.headerLayout);
    ViewTreeObserver observer = headerLayout .getViewTreeObserver();
            observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {
            // TODO Auto-generated method stub
            int headerLayoutHeight= headerLayout.getHeight();
        int headerLayoutWidth = headerLayout.getWidth();
        headerLayout .getViewTreeObserver().removeGlobalOnLayoutListener(
                this);
    }
});


}  

#2


7  

getWidth() is giving you 0 because onCreate is called before layout actually happens. Due to views being able to have dynamic positions and sizes based on attributes or other elements (fill_parent for example) there's not a fixed size for any given view or layout. At runtime there is a point in time (actually it can happen repeatedly depending on many factors) where everything is actually measured and laid out. If you really need the height and width, you'll have to get them later as you've discovered.

getWidth()给你0,因为在布局实际发生之前,onCreate被调用。由于视图能够基于属性或其他元素(例如fill_parent)具有动态位置和大小,所以对于任何给定的视图或布局都没有固定的大小。在运行时,会有一个时间点(实际上,它可以根据许多因素反复发生),在这个时间点上,所有的东西都被实际测量和布置。如果你真的需要高度和宽度,你将不得不在你发现之后得到它们。

#3


3  

This specially deal with Dimensions so

这是专门处理维数的。

Display display = getWindowManager().getDefaultDisplay(); 
int width = display.getWidth(); 
int height = display.getHeight();

This may help you in managing dimensions.

这可能有助于您管理维度。

Note: This returns the display dimensions in pixels - as expected. But the getWidth() and getHeight() methods are deprecated. Instead you can use:

注意:这将返回以像素为单位的显示尺寸——如预期的那样。但是不赞成使用getWidth()和getHeight()方法。相反,您可以使用:

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;

as also Martin Koubek suggested.

正如马丁•库贝克(Martin Koubek)所建议的那样。

#4


2  

If your goal is to simply draw an oval on the screen, then consider creating your own custom View rather than messing around with AbsoluteLayout. Your custom View must override onDraw(android.graphics.Canvas), which will be called when the view should render its content.

如果你的目标只是在屏幕上画一个椭圆,那么考虑创建你自己的自定义视图,而不是搞得一团糟。您的自定义视图必须覆盖onDraw(android.graphics.Canvas),当视图呈现内容时将调用它。

Here is some extremely simple sample code that might help get you started:

下面是一些非常简单的示例代码,可以帮助您入门:

public class MainActivity extends Activity {

    private final Paint mPaint = new Paint();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new SampleView(this));
    }

    // create a nested custom view class that can draw an oval. if the
    // "SampleView" is not specific to the Activity, put the class in 
    // a new file called "SampleView.java" and make the class public 
    // and non-static so that other Activities can use it. 
    private static class SampleView extends View {
        public SampleView(Context context) {
            super(context);
            setFocusable(true);
        }

        @Override
        protected void onDraw(Canvas canvas) {
            canvas.drawColor(Color.CYAN);

            // smoothen edges
            mPaint.setAntiAlias(true);
            mPaint.setColor(Color.RED);
            mPaint.setStyle(Paint.Style.STROKE); 
            mPaint.setStrokeWidth(4.5f);

            // set alpha value (opacity)
            mPaint.setAlpha(0x80);

            // draw oval on canvas
            canvas.drawOval(new RectF(50, 50, 20, 40), mPaint);
        }
    }
}

#5


2  

This give you screen resolution:

这给你屏幕分辨率:

 WindowManager wm = (WindowManager)context.getSystemService(context.WINDOW_SERVICE);
 Display display = wm.getDefaultDisplay();
 Point outSize = new Point();
 display.getSize(outSize);

#6


1  

kabuko's answer is correct, but could be a little more clear, so let me clarify.

kabuko的答案是正确的,但是可能会更清楚一些,所以让我澄清一下。

getWidth() and getHeight() are (correctly) giving you 0 because they have not been drawn in the layout when you call them. try calling the two methods on the button after addView() (after the view has been drawn and is present in the layout) and see if that gives you the expected result.

getWidth()和getHeight()会(正确地)给您0,因为在调用它们时,它们并没有被绘制到布局中。尝试在addView()之后调用按钮上的这两个方法(在视图被绘制并显示在布局中之后),看看是否会得到预期的结果。

See this post for more information.

更多信息请参见本文。