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

4

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

如果视图与父视图底部对齐,我想将其与父视图顶部对齐,反之亦然。我能够按照自己的意愿对齐视图,但我不知道如何首先检查它。

我的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 >

我的代码:

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);

我无法使用getRule(),因为它只适用于API23及以上版本,而我是在API16上使用。

有什么帮助可以找到这个问题吗?谢谢。

1个回答

2
简单来说,您可以使用一个标志变量来实现以下操作:
    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标志,因为检查isTopAligned就足够了。


是的,我考虑过,但由于我在一个GridView中使用此布局,将会有多个实例。而且我不想使用flag。但如果没有其他选择,我将不得不使用它。 另外,我想知道是否有一种方法可以访问视图的这些布局参数(除了高度和宽度)。 - fractal5

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接