1

I am subclassing LinearLayout. In the subclass I can't figure out how to get the gravity value. I simply want to determine if the gravity set in xml layout is Gravity.LEFT or Gravity.RIGHT

Thanks in advance for any help.

4
  • getchild(index) can help. if index is 1, its the left/top most item in the list Nov 17, 2014 at 4:26
  • First try to get layout params of parent layout and get gravity value from layout params. Nov 17, 2014 at 4:41
  • @Haresh can't get gravity from getLayoutParams(). Can you give an example. Thx
    – Sohaib
    Nov 17, 2014 at 4:49
  • Have you cast getLayoutParams() to LinearLayout.getLayoutParams() after try to get gravity value. Nov 17, 2014 at 4:52

2 Answers 2

1

Try to get gravity from parent layout params :

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.
}
5
  • 1
    If gravity value in xml is something like this right|center_vertical then how to check?
    – Sohaib
    Nov 17, 2014 at 5:08
  • @Sohaib,Very good question man i dont think about it but it is very interesting now!!! Nov 17, 2014 at 5:11
  • I think proper way to check whether gravity is LEFT is something like this (gravity & Gravity.LEFT) == Gravity.LEFT
    – Sohaib
    Nov 17, 2014 at 5:34
  • Accepting your answer. Thanks for all the help Haresh
    – Sohaib
    Nov 17, 2014 at 5:35
  • No here no need check such kind of condition becz Gravity.LEFT return constant int value. Nov 17, 2014 at 5:37
0

The proper way to check for gravity should be using the bitmask.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.