문제

I am having a dynamic layout where there is a imagebutton named ButtonQ. I would like to set the dimension of the ButtonQ and then to see if it is correct, I have added a toast.

@Override
protected void onStart() 
{
    super.onStart();
    measure_dimension();
}


    private static Point getDisplaySize(final Display display) 
    {
        final Point point = new Point();
        try {
            display.getSize(point);
        } catch (java.lang.NoSuchMethodError ignore) { // Older device
            point.x = display.getWidth();
            point.y = display.getHeight();
        }
        return point;
    }

    public void measure_dimension() 
    { 
        Display display = getWindowManager().getDefaultDisplay();
        Point size = getDisplaySize(display); 
        int screen_width = size.x;
        int screen_height = size.y;

        int target_height = Math.min(screen_height, 600);
        int target_width = Math.min(screen_width, 600);
        int target_dimension = Math.min(target_height, target_width);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(target_dimension, target_dimension);  // width, height
        buttonQ.setLayoutParams(layoutParams); 
        image_height = target_height;
        image_width = target_width;

        Toast.makeText(Game_middle.this, "buttonQ height:"+ buttonQ.getHeight() +"\nbuttonQ width=" + buttonQ.getWidth(), Toast.LENGTH_LONG).show();
}

Question:

The toast reports the height and the width of ButtonQ are both 0. Why?

도움이 되었습니까?

해결책

I'd use the analogue way you're setting your height and width: via getLayoutParams(). If you want to set the params dynamically, I wouldn't use pixels directly but the dp unit, using TypedValue.COMPLEX_UNIT_DIP.

Regarding to synchronization, in that example I'd definitely use asynchronous mechanisms, such as CountDownLatch or Semaphore mechanisms. It's quite more secure this way than using temporary timers. You may want to check the CountDownLatch(1) example in the reference page for that purpose.

다른 팁

Try this to get the button dimensions where popLayout is the button name in your case

popupLayout.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
width = popupLayout.getMeasuredWidth();
height = popupLayout.getMeasuredHeight();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top