2013-10-22 122 views
0

我有一个以标题为中心的相对布局和右对齐的取消按钮。 我想检查标题是否与取消按钮重叠,如果是,我将根据它的重叠程度将标题左移。获取视图的位置

这是我的XML的外观:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res/com.app.mobile" 
    android:orientation="vertical" android:layout_width="match_parent" 
    android:layout_height="@dimen/actionBarHeight" 
    android:layout_alignParentTop="true" 
    android:id="@+id/actionbar" 
    android:background="#F8F8F8"> 

    <com.app.mobile.subview.CustomButton android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentRight="true" 
     android:id="@+id/cancel_btn" 
     android:text="Cancel" 
     app:typeface="fonts/HelveticaNeue" 
     app:customStyle="Regular" 
     android:textSize="@dimen/titleTextSize" 
     android:textColor="#378BFB" 
     android:background="@android:color/transparent" 
     android:layout_centerVertical="true" 
     android:layout_marginRight="10dp" 
     android:layout_marginLeft="10dp" 
     android:visibility="gone"/> 

    <com.app.mobile.subview.CustomButton android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentRight="true" 
     android:id="@+id/share_btn" 
     app:typeface="fonts/HelveticaNeue" 
     app:customStyle="Regular" 
     android:textColor="#378BFB" 
     android:visibility="gone"/> 

    <com.app.mobile.subview.CustomTextView 
     android:id="@+id/title" 
     android:gravity="center" 
     android:layout_centerInParent="true" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     app:typeface="fonts/HelveticaNeue" 
     app:customStyle="Medium" 
     android:textSize="@dimen/titleTextSize" 
     android:textColor="#000" 
     android:text="Test Title"/> 
</RelativeLayout> 

而我试图让像下面

float xPos = screenTitle.getX(); 
    float titleEnd = xPos + screenTitle.getWidth(); 
    xPos = cancelButton.getX(); 

    if(titleEnd > xPos){ 
     Log.e("Title","Title overlaps cancel button"); 
    } 

cancelButton.getX()将返回我0.0,而标题返回正确的位置值。

1.本是布局如何与小题

http://i.stack.imgur.com/3TFdg.jpg

+0

2.具有非常大的标题 http://i.stack.imgur.com/8aT2M.jpg 3.这是它是如何应该看起来具有非常大的标题 HTTP://i.stack .imgur.com/YNufR.jpg – Uma

回答

1

它取决于是否在Java代码中你试图获得的getX()

如果Android的价值尚未完成绘制整个布局,cancelButton尚未绘制,X为0.0。

我发现,在获得的onCreate()或onCreateView()的值是很容易的用后可运行和

cancelButton.post(new Runnable() { 
    @Override 
    public void run() { 
      float x = cancelButton.getX(); 

     } 
    }); 

这确保了按键已经完全绘制您尝试使用前值

+0

它工作!谢谢!! – Uma