2012-03-09 59 views
2

如何訪問您的自定義視圖的android:layout_width和android:layout_height值?如何訪問自定義視圖的android:layout_width和android:layout_height參數?

示例XML:

<com.example.CustomButton 
    android:id="@+id/btn" 
    android:layout_width="150dp" 
    android:layout_height="70dp" /> 

在的CustomButton:

@Override 
protected void onMeasure(int widthSpec, int heightSpec) { 
    int measuredWidth = MeasureSpec.getSize(widthSpec); 
    int measuredHeight = MeasureSpec.getSize(heightSpec); 
    // How can we measure based on android:layout_width, android:layout_height? 
    // Currently this implementation measures off the parent's values 
    setMeasuredDimension(measuredWidth, measuredHeight); 
} 

回答

4

你必須得到視圖的佈局PARAMS:

CustomButton.LayoutParams viewParams = yourView.getLayoutParams(); 

然後你就可以訪問或修改寬度或查看:

viewParams.height; 
viewParams.width; 

希望它有幫助!

+0

正是我在找的感謝! – Dude 2012-03-09 16:38:19

相關問題