Android:检查视图是否以编程方式与父视图底部/顶部对齐

Android:检查视图是否以编程方式与父视图底部/顶部对齐,android,layout,layoutparams,Android,Layout,Layoutparams,如何检查视图是否与父视图底部(或顶部)对齐 如果视图与父视图底部对齐,我希望将其与父视图顶部对齐,反之亦然。我可以根据需要对齐视图,但我不知道如何首先检查它 我的XML: < RelativeLayout android:layout_width="20dp" android:layout_height="200dp"> < Button android:id="@+id/mybutton"

如何检查视图是否与父视图底部(或顶部)对齐

如果视图与父视图底部对齐,我希望将其与父视图顶部对齐,反之亦然。我可以根据需要对齐视图,但我不知道如何首先检查它

我的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 >
我不能使用getRule(),因为它只对API23及以上版本有效,并且我从API16开始使用它


有人能帮我找到这个吗?谢谢。

很简单,您可以使用一个标志变量来实现此目的,如下所示:

    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);
我认为不需要更多的细化,因为代码很容易理解


注意:不需要isBottomAligned标志,因为检查istpaligned就足够了。

是的,我考虑过,但因为我在gridview中使用此布局,所以将有多个实例。我宁愿不使用国旗。但如果没有其他选择,我将不得不这样做。另外,我想知道是否有办法访问视图的此类布局参数(除了高度和宽度)。
    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);