对LinearLayout进行子类化,如何确定重力是LEFT还是RIGHT

时间:2014-11-17 04:17:36

标签: android android-linearlayout

我是LinearLayout的子类。在子类中,我无法弄清楚如何获得重力值。我只是想确定xml布局中设置的重力是Gravity.LEFT还是Gravity.RIGHT

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

尝试从父布局参数中获取引力:

int gravity = ((LinearLayout.LayoutParams)((LinearLayout)childView.getParent()).getLayoutParams()).gravity;
if(gravity == Gravity.LEFT){
   // write your code when parent gravity is left           
}else if(gravity == Gravity.RIGHT){
   // write your code when parent gravity is right           
}else if(gravity == (Gravity.LEFT | Gravity.CENTER_VERTICAL)){
  // write your code when parent gravity is left with center vertical
else{
  // write your code when parent gravity is neither right nor left.
}

答案 1 :(得分:0)

检查重力的正确方法应该是使用位掩码。

if ((gravity & Gravity.END) == Gravity.END) {
    // end/right justified
} 
if ((gravity & Gravity.CENTER_VERTICAL) == Gravity.CENTER_VERTICAL) {
    // center vertical
}
etc..