2016-09-29 3 views
0

Кажется очень простым, но почему-то я не могу понять, как найти координату слева (x) и top (y). Я пробовал почти каждый ответ, каждый дает нуль.Найти точную координату вида на экране Android

Вот XML

<?xml version="1.0" encoding="utf-8"?> 
<android.support.v4.widget.DrawerLayout  
xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:app="http://schemas.android.com/apk/res-auto" 
android:id="@+id/drawer_layout" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:fitsSystemWindows="true"> 

<include layout="@layout/include_list_viewpager" /> 

<android.support.design.widget.NavigationView 
    android:id="@+id/nav_view" 
    android:layout_width="wrap_content" 
    android:layout_height="match_parent" 
    android:layout_gravity="start" 
    android:fitsSystemWindows="true" 
    app:headerLayout="@layout/nav_header" 
    app:menu="@menu/drawer_view" /> 

include_list_viewpager.xml

<android.support.design.widget.CoordinatorLayout  
    xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:app="http://schemas.android.com/apk/res-auto" 
xmlns:tools="http://schemas.android.com/tools" 
android:id="@+id/main_content" 
android:layout_width="match_parent" 
android:layout_height="match_parent"> 

<android.support.design.widget.AppBarLayout 
    android:id="@+id/appbar" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"> 

    <android.support.v7.widget.Toolbar 
     android:id="@+id/toolbar" 
     android:layout_width="match_parent" 
     android:layout_height="?attr/actionBarSize" 
     android:background="?attr/colorPrimary" 
     app:layout_scrollFlags="scroll|enterAlways" 
     app:popupTheme="@style/ThemeOverlay.AppCompat.Light" /> 

    <AutoCompleteTextView 
     android:id="@+id/et_inputSearch" 
     android:layout_width="match_parent" 
     android:layout_height="@dimen/abc_action_bar_stacked_max_height" 
     android:layout_marginLeft="@dimen/tiny_margin" 
     android:layout_marginRight="@dimen/tiny_margin" 
     android:layout_marginTop="@dimen/tiny_margin" 
     android:background="@drawable/edit_text_rounded_with_background_register" 
     android:completionThreshold="1" 
     android:drawableLeft="@drawable/ic_search_black_24dp" 
     android:drawablePadding="@dimen/default_margin" 
     android:hint="@string/msg_hint_search_text_box" 
     android:imeOptions="actionSearch" 
     android:inputType="textCapSentences|textAutoCorrect" 
     android:maxLines="1" 
     android:paddingLeft="@dimen/horizontal_margin" 
     android:textColor="@color/colorPrimaryText" 
     android:textColorHint="@color/divider" 
     android:textSize="@dimen/info_text_heading" /> 

    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="40dp" 
     android:orientation="horizontal"> 

     <LinearLayout 
      android:id="@+id/btn_filter" 
      style="@style/Base.Widget.AppCompat.Button.Borderless" 
      android:layout_width="0dp" 
      android:layout_height="wrap_content" 
      android:layout_weight="1" 
      android:gravity="center" 
      android:orientation="horizontal"> 

      <FrameLayout 
       android:id="@+id/frame_filter" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content"> 

       <TextView 
        android:id="@+id/tv_text_filter" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:drawableLeft="@drawable/ic_filter" 
        android:drawablePadding="@dimen/tiny_margin" 
        android:gravity="center" 
        android:text="@string/txt_filter" 
        android:textAllCaps="false" 
        android:textColor="@color/white" /> 

       <TextView 
        android:id="@+id/tv_filter" 
        android:layout_width="15dp" 
        android:layout_height="15dp" 
        android:layout_gravity="top|left" 
        android:background="@drawable/badge_filter_fab" 
        android:gravity="center" 
        android:textColor="@color/white" 
        android:textSize="10sp" 
        android:visibility="gone" /> 
      </FrameLayout> 

     </LinearLayout> 

     <View 
      android:layout_width="1px" 
      android:layout_height="20dp" 
      android:layout_gravity="center" 
      android:background="@color/white" /> 

     <LinearLayout 
      android:id="@+id/btn_sort" 
      style="@style/Base.Widget.AppCompat.Button.Borderless" 
      android:layout_width="0dp" 
      android:layout_height="wrap_content" 
      android:layout_weight="1" 
      android:gravity="center" 
      android:orientation="horizontal"> 

      <TextView 
       android:id="@+id/tv_sort" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:drawableLeft="@drawable/ic_swap_vert_white_24dp" 
       android:gravity="center" 
       android:text="@string/txt_sort" 
       android:textAllCaps="false" 
       android:textColor="@color/white" /> 

      <TextView 
       android:id="@+id/tv_sort_by" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_gravity="bottom" 
       android:gravity="bottom" 
       android:paddingLeft="@dimen/tiny_margin" 
       android:text="@string/text_default" 
       android:textColor="@color/white" 
       android:textSize="10sp" /> 

     </LinearLayout> 

    </LinearLayout> 
</android.support.design.widget.AppBarLayout> 

<fragment 
    android:id="@+id/fragment_container" 
    android:name="in.workindia.nileshdungarwal.workindiaandroid.fragments.FragJobAllList" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    app:layout_behavior="@string/appbar_scrolling_view_behavior" 
    tools:layout="@layout/fragment_job_list" /> 

<FrameLayout 
    android:id="@+id/fl_bottom_container" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_gravity="end|bottom" 
    android:layout_marginBottom="@dimen/default_margin" 
    android:layout_marginRight="@dimen/default_margin"> 

    <android.support.design.widget.FloatingActionButton xmlns:android="http://schemas.android.com/apk/res/android" 
     android:id="@+id/fab" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:onClick="onFabClick" 
     app:borderWidth="0dp" /> 

    <TextView 
     android:id="@+id/tv_on_float" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_gravity="center" 
     android:elevation="12dp" 
     android:text="NEW" 
     android:textColor="@android:color/white" /> 
</FrameLayout> 

**Code snippet to find out co-ordinate** 
private void showUseSearch() { 

    View etSearchTextList = findViewById(R.id.et_inputSearch); 
    int[] tableLayoutCorners = new int[2]; 

    Rect myViewRect = new Rect(); 
    etSearchTextList.getGlobalVisibleRect(myViewRect); 
    float x = myViewRect.left; 
    float y = myViewRect.top; 

    etSearchTextList.getLocationInWindow(tableLayoutCorners); 

    Log.i(TAG, x+","+y+"-"+tableLayoutCorners[0] + "-" + tableLayoutCorners[1] + ",showUseSearch: " + etSearchTextList.getX() + "," + etSearchTextList.getY() + "-" + etSearchTextList.getPivotX() + "-" + etSearchTextList.getPivotY()); 
    } 
+0

если вы просто звоните yourlayout.getX() и yourlayout.getY(), это даст вам верхнюю левую точку самому – Jai

+0

Помните, что представление должно быть выложено. Таким образом, вы не можете сделать это внутри, т.е. 'Activity'' onCreate', если вы не используете ['ViewTreeObserver.OnGlobalLayoutListener'] (https://developer.android.com/reference/android/view/ViewTreeObserver.OnGlobalLayoutListener.html). –

ответ

1

Если вы будете пытаться получить позицию до полного рендеринга пользовательского интерфейса вам ш плохо получишь его. Вы можете использовать прослушиватель treeObserver, чтобы получить x и y после привязки к пользовательскому интерфейсу. здесь вы идете:

view.getViewTreeObserver().addOnGlobalLayoutListener(
    new ViewTreeObserver.OnGlobalLayoutListener() { 
     @Override 
     public void onGlobalLayout() { 
      // Layout has happened here. 
      int x = (int)view.getX();// returns float 
      int y = (int)view.getY(); 

      // Don't forget to remove your listener when you are done with it. 
      view.getViewTreeObserver().removeOnGlobalLayoutListener(this); 
     } 
    }); 
+0

На самом деле, это был случай, мой метод пытался извлечь, даже если даже сделать так. Если я звоню из public void onGlobalLayout(), все работает отлично. –

+0

да, и чтобы получить верхний левый x y, нам не нужно принимать RECT или что-то в этом роде. getx gety даст себе – Jai

+0

@LokeshTiwari: Извините, что что-то пошло не так во время редактирования! вы можете редактировать снова, чтобы отразить – Jai

Смежные вопросы