2010-10-15 32 views
5

Tôi đang làm việc trên bố cục trong Android XML, trong đó tôi muốn đặt chiều cao của nút để khớp với chiều rộng của nút khi thiết lập để điền vào cha mẹ. Rõ ràng con số này sẽ thay đổi dựa trên kích thước màn hình, vì vậy tôi không thể sử dụng kích thước pixel được thiết lập. Ai đó có thể giúp tôi với chiều rộng nút dựa trên kích thước màn hình và sau đó đi qua đó để thiết lập chiều cao?Android: Đặt chiều cao nút trong XML dựa trên chiều rộng của nó

cảm ơn, Josh

Trả lời

-1

Thay vì sử dụng kích thước Pixel bởi PX, đề cập đến nhúng (ví dụ: thiết bị điểm ảnh độc lập), nhúng sẽ lấy kích thước theo pixel theo thiết bị kích thước màn hình một cách độc lập.

ví dụ: android: textSize = "12dip"

Bạn có thể sử dụng nhúng hoặc dp.

Tận hưởng !!

3

Tôi đã từng gặp vấn đề tương tự và không tìm thấy giải pháp nào hoạt động chỉ từ XML. Bạn phải viết Button-Class của riêng bạn và ghi đè lên phương pháp [onMeassure] [1].

Ví dụ:

/** 
* @see android.view.View#measure(int, int) 
*/ 
@Override 
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
    setMeasuredDimension(measureWidth(widthMeasureSpec), measureHeight(heightMeasureSpec)); 
} 

private int width; // saves the meassured width 


/** 
* Determines the width of this view 
* 
* @param measureSpec 
*   A measureSpec packed into an int 
* @return The width of the view, honoring constraints from measureSpec 
*/ 
private int measureWidth(int measureSpec) { 
    int result = 30; 
    int specMode = MeasureSpec.getMode(measureSpec); 
    int specSize = MeasureSpec.getSize(measureSpec); 

    if (specMode == MeasureSpec.EXACTLY) { 
     // We were told how big to be 
     result = specSize; 
    } else { 
     result =1123; // meassure your with here somehow 
     if (specMode == MeasureSpec.AT_MOST) { 
      // Respect AT_MOST value if that was what is called for by measureSpec 
      result = Math.min(result, specSize); 
     } 
    } 
      width = result; 
    return result; 
} 

/** 
* Determines the height of this view 
* 
* @param measureSpec 
*   A measureSpec packed into an int 
* @return The height of the view, honoring constraints from measureSpec 
*/ 
private int measureHeight(int measureSpec) { 
    int result = 0; 
    int specMode = MeasureSpec.getMode(measureSpec); 
    int specSize = MeasureSpec.getSize(measureSpec); 

    if (specMode == MeasureSpec.EXACTLY) { 
     // We were told how big to be 
     result = specSize; 
    } else { 
     result = width; 
     if (specMode == MeasureSpec.AT_MOST) { 
      // Respect AT_MOST value if that was what is called for by measureSpec 
      result = Math.min(result, specSize); 
     } 
    } 

    return result; 
} 

[1]: http://developer.android.com/reference/android/view/View.html#onMeasure(int, int)

Các vấn đề liên quan