2012-07-24 17 views
6

Estoy tratando de hacer que una ventana emergente aparezca encima/debajo de un elemento que se hace clic dentro de un ListView. Sin embargo, el problema es que la Vista que viene desde el método OnItemClick solo me está dando sus valores X & relativos al ListView. También verifiqué el ListView y eso también me da x = 0 y = 0 a pesar del hecho de que hay otras vistas sobre él.Obtener posición de vista absoluta en ListView

Revisé todos los valores en hierarchyviewer, pero no vi los valores que estaba buscando. (Y no estoy teniendo grandes problemas para que vuelva a funcionar).

¿Algún consejo?

@Override 
public void onListItemClick(ListView listView, View view, int position, long id) { 
    LayoutInflater inflater = getLayoutInflater(null); 
    PopupWindow quickRail = new PopupWindow(
      inflater.inflate(R.layout.quanitity_controls, null), view.getMeasuredWidth(), 
      view.getMeasuredHeight()); 

    int[] location = { 
      0, 0 
    }; 

    // This doesn't place this window right on top of the view 
    quickRail.showAtLocation(view, Gravity.CENTER, 0, location[1]); 
} 

Ambos elementos en la lista están haciendo que la ventana emergente aparezca en el mismo lugar. Popup Not Appearing In desired positions

Respuesta

8

Esto debería funcionar

//Activity windows height 
int totalHeight = getWindowManager().getDefaultDisplay().getHeight(); 
int[] location = new int[2]; 
v.getLocationOnScreen(location); 

La matriz de ubicación debe tener los valores xey de la vista. 'v' es el objeto de vista que se pasa en onItemClickListener.

Im añadiendo algunas partes que utilicé para mi proyecto. Puede ser útil. Tenía una barra de acciones en la parte superior de la vista de lista y este código parecía funcionar bien.

El requisito era traer un pequeño menú en la parte superior o inferior de un elemento de la lista. Por lo tanto, cuando se selecciona un elemento, compruebo si el elemento de la lista seleccionada se encuentra en la mitad superior de la pantalla, de ser así, coloque el menú debajo del elemento de la lista, de lo contrario colóquelo encima del elemento de la lista. Aquí está el código

código ListItem clic

listView.setOnItemClickListener(new OnItemClickListener() { 
    public void onItemClick(AdapterView<?> parent, View view, int position 
      , long id) { 
     showQuickActionMenu(position,view); 
    } 
}); 

private void showQuickActionMenu(int pos, View v){ 
    LayoutInflater inflater = 
      (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

    //This is just a view with buttons that act as a menu. 
    View popupView = inflater.inflate(R.layout.ticket_list_menu, null); 
    popupView.findViewById(R.id.menu_view).setTag(pos); 
    popupView.findViewById(R.id.menu_change_status).setTag(pos); 
    popupView.findViewById(R.id.menu_add_note).setTag(pos); 
    popupView.findViewById(R.id.menu_add_attachment).setTag(pos); 

    window = PopupHelper.newBasicPopupWindow(TicketList.this); 
    window.setContentView(popupView); 
    int totalHeight = getWindowManager().getDefaultDisplay().getHeight(); 
    int[] location = new int[2]; 
    v.getLocationOnScreen(location); 

    if (location[1] < (totalHeight/2.0)) { 
     PopupHelper.showLikeQuickAction(window, popupView, v 
       , getWindowManager(),0,0,PopupHelper.UPPER_HALF); 
    } else { 
     PopupHelper.showLikeQuickAction(window, popupView, v 
       , getWindowManager(),0, 0,PopupHelper.LOWER_HALF); 
    } 
} 

Esta clase del PopupHelper utilizo

public class PopupHelper { 
    public static final int UPPER_HALF = 0; 
    public static final int LOWER_HALF = 1; 

    public static PopupWindow newBasicPopupWindow(Context context) { 
     final PopupWindow window = new PopupWindow(context); 

     // when a touch even happens outside of the window 
     // make the window go away 
     window.setTouchInterceptor(new OnTouchListener() { 
      public boolean onTouch(View v, MotionEvent event) { 
       if(event.getAction() == MotionEvent.ACTION_OUTSIDE) { 
        window.dismiss(); 
        return true; 
       } 
       return false; 
      } 
     }); 

     window.setWidth(WindowManager.LayoutParams.WRAP_CONTENT); 
     window.setHeight(WindowManager.LayoutParams.WRAP_CONTENT); 
     window.setTouchable(true); 
     window.setFocusable(true); 
     window.setOutsideTouchable(true); 

     window.setBackgroundDrawable(
       new ColorDrawable(android.R.color.darker_gray));   
     return window; 
    } 

    /** 
    * Displays like a QuickAction from the anchor view. 
    * 
    * @param xOffset 
    *   offset in the X direction 
    * @param yOffset 
    *   offset in the Y direction 
    */ 
    public static void showLikeQuickAction(PopupWindow window, View root, 
      View anchor, WindowManager windowManager, int xOffset 
      ,int yOffset,int section) { 

     //window.setAnimationStyle(R.style.Animations_GrowFromBottomRight); 

     int[] location = new int[2]; 
     anchor.getLocationOnScreen(location); 

     Rect anchorRect = new Rect(location[0], location[1], location[0] + 
       anchor.getWidth(), location[1] + anchor.getHeight()); 

     root.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 

     int rootWidth = root.getMeasuredWidth(); 
     int rootHeight = root.getMeasuredHeight(); 

     int screenWidth = windowManager.getDefaultDisplay().getWidth(); 
     int screenHeight = windowManager.getDefaultDisplay().getHeight(); 

     int xPos = ((screenWidth - rootWidth)/2) + xOffset; 
     int yPos = anchorRect.top - rootHeight + yOffset; 

     xPos = (screenWidth - rootWidth); 
     if(section == UPPER_HALF){ 
      yPos = anchorRect.top + anchor.getMeasuredHeight();  
     } else { 
      yPos = anchorRect.top - rootHeight; 
     } 
     window.showAtLocation(anchor, Gravity.NO_GRAVITY, xPos, yPos); 
    } 

} 
+0

Gracias por esto, pero probé esto y solo me da la posición relativa. Entonces el primer elemento es la lista es 0,0. Está cerca, porque pensé que esa también era la solución. Creo que estoy teniendo algunos problemas de traducción en alguna parte. –

+0

puedes poner tu diseño xml. Tenía un poco el mismo requisito, pero mi diseño solo tenía una lista. – blessenm

+0

He actualizado mi respuesta. – blessenm

0

probar esto y ver si funciona ..

private void setListViewHeightBasedOnChildren(ListView listView) { 
    ListAdapter listAdapter = listView.getAdapter(); 
    if (listAdapter == null) { 
     // pre-condition 
     return; 
    } 
    int totalHeight = 0; 
    int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(), MeasureSpec.AT_MOST); 
    for (int i = 0; i < listAdapter.getCount(); i++) { 
     View listItem = listAdapter.getView(i, null, listView); 
     listItem.measure(desiredWidth, MeasureSpec.UNSPECIFIED); 
     totalHeight += listItem.getMeasuredHeight(); 
    } 

}

// aquí listItem.getMeasuredHeight() u obtendrá la altura de cada elemento de la lista ... U puede conseguir ur y la posición de altura * clickedPosition

+0

Gracias por la respuesta. No tengo problemas para obtener el alto de la lista. Estoy tratando de obtener las coordenadas de la pantalla de una vista para que pueda mostrar una ventana emergente. –

1

para los que se quedan en este tema utilización probar este fragmento de código

popWindow.showAsDropDown(v);//v is your listview or recyclerview item Element that clicked. 

espero que esta ayuda.

Cuestiones relacionadas