4

How can I check if my view is aligned to it's parent bottom (or top).

If the view is aligned to the parent bottom, I want to align it to the parent top, and vice versa. I am able to align the view as I want but I don't know how to check it first.

My XML:

< RelativeLayout
    android:layout_width="20dp"
    android:layout_height="200dp">
        < Button 
            android:id="@+id/mybutton"     
            android:layout_height="25dp"       
            android:layout_alignParentBottom="true"
            android:layout_width="match_parent">
        < / Button>
< / RelativeLayout >

My code:

Button mybutton = (Button) findViewById(R.id.mybutton);
LayoutParams params1 = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, 25);
params1.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, 0);
params1.addRule(RelativeLayout.ALIGN_PARENT_TOP);
button.setLayoutParams(params1);

I can't use getRule() since that is only valid for API23 and above, and I'm using since API16.

Any help on what I can do to find this? Thanks.

fractal5
  • 2,034
  • 4
  • 29
  • 50

1 Answers1

2

Its Simple, You can use one flag variable to achive this as below :

    int isTopAligned=0;
    int isBottomAligned=0;
    Button mybutton = (Button) findViewById(R.id.mybutton);
    LayoutParams params1 = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, 25);
    if(isTopAligned==0){
       params1.addRule(RelativeLayout.ALIGN_PARENT_TOP);
       params1.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM,0);
       isTopAligned=1;
       isBottomAligned=0;
     }
     else{
       params1.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
       params1.addRule(RelativeLayout.ALIGN_PARENT_TOP,0);
       isTopAligned=0;
       isBottomAligned=1;
     }
     button.setLayoutParams(params1);

I think there is no more elaboration required, as the code is simple to understand.

Note: isBottomAligned flag is not needed, since checking for isTopAligned is enough.

fractal5
  • 2,034
  • 4
  • 29
  • 50
user5716019
  • 598
  • 4
  • 17
  • Yeah I considered that, but since I'm using this layout in a gridview, there are going to be multiple instances of them. And I would prefer not to use flag. But if there is no other option I will have to. Plus, I would like to know if there is a way to access such layout params of a view (apart from height and width). – fractal5 Feb 09 '16 at 12:46