2

He estado buscando pero siempre dicen hacer un RecyclerView y a mí eso se me descuadra, el ListView es lo que necesito, pero en horizontal, y es diferente al vertical y no me sale:

He intentado poner:

activity_main.xml:

<ListView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/listView" />

Y el .java lo de este link: http://www.androidconnect.org/2012/05/10/como-hacer-listview-horizontales/ pero me da muchas cosas en rojo en código que no puedo solucionar, por lo que no me sirve como solución.

Sólo me hace falta poner un icono , nada de botones ni nada, solo un icono, ni tampoco me haría falta en principio el onClick , pero no estaría de más. ¿ Alguien ha usado alguna vez esto en horizontal?

Código de mi Layout:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:background="@drawable/border"
    android:orientation="horizontal">

    <ListView
        android:id="@+id/list_item"
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_height="wrap_content">

              //ESTE LISTVIEW DEBE SER EL RECYCLER PERO 
              // SI LO PONGO COMO RECYCLER ME SALE ERROR Y NO 
              //SE ME QUEDA DEL MISMO TAMAÑO QUE EL LISTVIEW     

            </ListView>


</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="4"
    android:orientation="vertical">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="2"
        android:orientation="horizontal"
        android:weightSum="2">


        <ImageButton
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/border_superior_izquierdo"
            android:src="@drawable/imagen_cambiante_teleco" />

        <ImageButton
            android:id="@+id/imageButton"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/border_rojo"
            android:src="@drawable/youtube1" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="2"
        android:orientation="horizontal"
        android:weightSum="2">


        <ImageButton
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/border_inferior_izquierdo"
            android:src="@drawable/salidas2" />

        <ImageButton
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/border_inferior_derecho"
            android:src="@drawable/paraq" />
    </LinearLayout>
</LinearLayout>

6
  • Si todos te decimos recyclerview es por algo. Listview esta anticuado, recyclerview es muchisimo mejor, es que no hay punto de comparacion y deberias replantearte tu decision porque de verdad lo vas a agradecer.
    – Curro
    el 27 mar. 2017 a las 19:47
  • En que se diferencia? Vale, entonces a la hora de poner recycler se me descuadra, lo pongo como actualizacion mi codigo del layout y donde iria mi recyclerview
    – Rf Mvs
    el 27 mar. 2017 a las 19:51
  • @Curro ya he actualizado, donde esta comentado, ahi debe ir el recycler,
    – Rf Mvs
    el 27 mar. 2017 a las 19:54
  • Y has importado en gradle la depencia para usar recyclerview???
    – Curro
    el 27 mar. 2017 a las 19:59
  • Sí, ahora si, pero no se me acopla bien, hago unas pruebas y vuelvo a comentar curro.
    – Rf Mvs
    el 27 mar. 2017 a las 20:00

2 respuestas 2

1

Definitivamente la opción es usar un RecyclerView en este caso, te recomiendo revisar la respuesta:

como puedo hacer un ListView horizontal en android?

La clave para crear un Listado horizontal mediante RecyclerView es obtener la instancia del RecyclerView:

 RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);

del layout:

   <android.support.v7.widget.RecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:scrollbars="horizontal"
    android:scrollbarStyle="outsideInset" />

y definirle un LinearLayoutManager de orientación Horizontal

//Horizontal orientation.
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));

Si deseas que tenga orientación vertical define al RecyclerView un LinearLayoutManager cuya orientación default es vertical.

   //Vertical orientation.
    recyclerView.setLayoutManager(new LinearLayoutManager(this));

Este es un ejemplo mostrando 2 RecyclerViews con ambas orientaciones:

introducir la descripción de la imagen aquí


Cuando deseas realizar una lista horizontal o vertical únicamente necesitas un RecyclerView.

Para cargar una imagen distinta en cada elemento, no necesitas cargar un layout diferente en el Adapter, simplemente crea un objeto que tenga como propiedad su url o ruta, al cargar el elemento mediante el Adapter tomará la imagen correspondiente.

introducir la descripción de la imagen aquí

Agrego link del ejemplo mostrado.

5
  • Hasta ahí sí, pero lo que me lía ahora es lo de poner "Haris", "Antoaneta"... y eso. Pues yo tengo 11 layout y en cada uno me hace falta poner iconos distintos, donde defino eso? Puedes actualizarla por favor como has hecho tu esas opciones? Lo estoy intentando con otro ejemplo de un listview pero no me sale y quiero usar ya siempre el recyclerView
    – Rf Mvs
    el 28 mar. 2017 a las 9:17
  • Estoy intentandolo sin exito.. como has logrado poner Antoaneta, constantin...y demas? Puedes ponerlo como actualizacion por favor?
    – Rf Mvs
    el 28 mar. 2017 a las 14:49
  • Hola @RfMvs, dame unos minutos, no necesitas varios layouts si solo cambian los valores del elemento, en este caso los valores los almacene en un array de objetos.
    – Jorgesys
    el 28 mar. 2017 a las 14:51
  • De acuerdo Jorgesys, sí, me hacen falta varios layouts, pues cada layout tiene una imagen distinta, por lo que de partida tengo 11 layouts, y tengo 11 recyclerView, pero ahora cuando actualices lo veo ^^
    – Rf Mvs
    el 28 mar. 2017 a las 14:57
  • Unicamente necesitas un RecyclerView y un layout si es que solo cambias la imagen pero el diseño del layout es el mismo, agrego actualización y ejemplo de como crear un Listado Horizontal, cargando imagenes distintas en cada elemento.
    – Jorgesys
    el 28 mar. 2017 a las 20:17
-1
  1. Crea un archivo ListViewHorizontal.class
  2. Puedes copiar a continuación:

import android.content.Context;
import android.database.DataSetObserver;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.Scroller;

import java.util.LinkedList;
import java.util.Queue;


public class ListViewHorizontal extends AdapterView<ListAdapter> {

    public boolean mAlwaysOverrideTouch = true;
    protected ListAdapter mAdapter;
    private int mLeftViewIndex = -1;
    private int mRightViewIndex = 0;
    protected int mCurrentX;
    protected int mNextX;
    private int mMaxX = Integer.MAX_VALUE;
    private int mDisplayOffset = 0;
    protected Scroller mScroller;
    private GestureDetector mGesture;
    private Queue<View> mRemovedViewQueue = new LinkedList<View>();
    private OnItemSelectedListener mOnItemSelected;
    private OnItemClickListener mOnItemClicked;
    private OnItemLongClickListener mOnItemLongClicked;
    private boolean mDataChanged = false;


    public ListViewHorizontal(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    private synchronized void initView() {
        mLeftViewIndex = -1;
        mRightViewIndex = 0;
        mDisplayOffset = 0;
        mCurrentX = 0;
        mNextX = 0;
        mMaxX = Integer.MAX_VALUE;
        mScroller = new Scroller(getContext());
        mGesture = new GestureDetector(getContext(), mOnGesture);
    }

    @Override
    public void setOnItemSelectedListener(AdapterView.OnItemSelectedListener listener) {
        mOnItemSelected = listener;
    }

    @Override
    public void setOnItemClickListener(AdapterView.OnItemClickListener listener){
        mOnItemClicked = listener;
    }

    @Override
    public void setOnItemLongClickListener(AdapterView.OnItemLongClickListener listener) {
        mOnItemLongClicked = listener;
    }

    private DataSetObserver mDataObserver = new DataSetObserver() {

        @Override
        public void onChanged() {
            synchronized(ListViewHorizontal.this){
                mDataChanged = true;
            }
            invalidate();
            requestLayout();
        }

        @Override
        public void onInvalidated() {
            reset();
            invalidate();
            requestLayout();
        }

    };

    @Override
    public ListAdapter getAdapter() {
        return mAdapter;
    }

    @Override
    public View getSelectedView() {
        //TODO: implement
        return null;
    }

    @Override
    public void setAdapter(ListAdapter adapter) {
        if(mAdapter != null) {
            mAdapter.unregisterDataSetObserver(mDataObserver);
        }
        mAdapter = adapter;
        mAdapter.registerDataSetObserver(mDataObserver);
        reset();
    }

    private synchronized void reset(){
        initView();
        removeAllViewsInLayout();
        requestLayout();
    }

    @Override
    public void setSelection(int position) {
        //TODO: implement
    }

    private void addAndMeasureChild(final View child, int viewPos) {
        LayoutParams params = child.getLayoutParams();
        if(params == null) {
            params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        }

        addViewInLayout(child, viewPos, params, true);
        child.measure(MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.AT_MOST),
                MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.AT_MOST));
    }



    @Override
    protected synchronized void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);

        if(mAdapter == null){
            return;
        }

        if(mDataChanged){
            int oldCurrentX = mCurrentX;
            initView();
            removeAllViewsInLayout();
            mNextX = oldCurrentX;
            mDataChanged = false;
        }

        if(mScroller.computeScrollOffset()){
            int scrollx = mScroller.getCurrX();
            mNextX = scrollx;
        }

        if(mNextX <= 0){
            mNextX = 0;
            mScroller.forceFinished(true);
        }
        if(mNextX >= mMaxX) {
            mNextX = mMaxX;
            mScroller.forceFinished(true);
        }

        int dx = mCurrentX - mNextX;

        removeNonVisibleItems(dx);
        fillList(dx);
        positionItems(dx);

        mCurrentX = mNextX;

        if(!mScroller.isFinished()){
            post(new Runnable(){
                @Override
                public void run() {
                    requestLayout();
                }
            });

        }
    }

    private void fillList(final int dx) {
        int edge = 0;
        View child = getChildAt(getChildCount()-1);
        if(child != null) {
            edge = child.getRight();
        }
        fillListRight(edge, dx);

        edge = 0;
        child = getChildAt(0);
        if(child != null) {
            edge = child.getLeft();
        }
        fillListLeft(edge, dx);


    }

    private void fillListRight(int rightEdge, final int dx) {
        while(rightEdge + dx < getWidth() && mRightViewIndex < mAdapter.getCount()) {

            View child = mAdapter.getView(mRightViewIndex, mRemovedViewQueue.poll(), this);
            addAndMeasureChild(child, -1);
            rightEdge += child.getMeasuredWidth();

            if(mRightViewIndex == mAdapter.getCount()-1) {
                mMaxX = mCurrentX + rightEdge - getWidth();
            }

            if (mMaxX < 0) {
                mMaxX = 0;
            }
            mRightViewIndex++;
        }

    }

    private void fillListLeft(int leftEdge, final int dx) {
        while(leftEdge + dx > 0 && mLeftViewIndex >= 0) {
            View child = mAdapter.getView(mLeftViewIndex, mRemovedViewQueue.poll(), this);
            addAndMeasureChild(child, 0);
            leftEdge -= child.getMeasuredWidth();
            mLeftViewIndex--;
            mDisplayOffset -= child.getMeasuredWidth();
        }
    }

    private void removeNonVisibleItems(final int dx) {
        View child = getChildAt(0);
        while(child != null && child.getRight() + dx <= 0) {
            mDisplayOffset += child.getMeasuredWidth();
            mRemovedViewQueue.offer(child);
            removeViewInLayout(child);
            mLeftViewIndex++;
            child = getChildAt(0);

        }

        child = getChildAt(getChildCount()-1);
        while(child != null && child.getLeft() + dx >= getWidth()) {
            mRemovedViewQueue.offer(child);
            removeViewInLayout(child);
            mRightViewIndex--;
            child = getChildAt(getChildCount()-1);
        }
    }

    private void positionItems(final int dx) {
        if(getChildCount() > 0){
            mDisplayOffset += dx;
            int left = mDisplayOffset;
            for(int i=0;i<getChildCount();i++){
                View child = getChildAt(i);
                int childWidth = child.getMeasuredWidth();
                child.layout(left, 0, left + childWidth, child.getMeasuredHeight());
                left += childWidth + child.getPaddingRight();
            }
        }
    }

    public synchronized void scrollTo(int x) {
        mScroller.startScroll(mNextX, 0, x - mNextX, 0);
        requestLayout();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        boolean handled = super.dispatchTouchEvent(ev);
        handled |= mGesture.onTouchEvent(ev);
        return handled;
    }

    protected boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                              float velocityY) {
        synchronized(ListViewHorizontal.this){
            mScroller.fling(mNextX, 0, (int)-velocityX, 0, 0, mMaxX, 0, 0);
        }
        requestLayout();

        return true;
    }

    protected boolean onDown(MotionEvent e) {
        mScroller.forceFinished(true);
        return true;
    }

    private OnGestureListener mOnGesture = new GestureDetector.SimpleOnGestureListener() {

        @Override
        public boolean onDown(MotionEvent e) {
            return ListViewHorizontal.this.onDown(e);
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                               float velocityY) {
            return ListViewHorizontal.this.onFling(e1, e2, velocityX, velocityY);
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2,
                                float distanceX, float distanceY) {

            synchronized(ListViewHorizontal.this){
                mNextX += (int)distanceX;
            }
            requestLayout();

            return true;
        }

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            for(int i=0;i<getChildCount();i++){
                View child = getChildAt(i);
                if (isEventWithinView(e, child)) {
                    if(mOnItemClicked != null){
                        mOnItemClicked.onItemClick(ListViewHorizontal.this, child, mLeftViewIndex + 1 + i, mAdapter.getItemId( mLeftViewIndex + 1 + i ));
                    }
                    if(mOnItemSelected != null){
                        mOnItemSelected.onItemSelected(ListViewHorizontal.this, child, mLeftViewIndex + 1 + i, mAdapter.getItemId( mLeftViewIndex + 1 + i ));
                    }
                    break;
                }

            }
            return true;
        }

        @Override
        public void onLongPress(MotionEvent e) {
            int childCount = getChildCount();
            for (int i = 0; i < childCount; i++) {
                View child = getChildAt(i);
                if (isEventWithinView(e, child)) {
                    if (mOnItemLongClicked != null) {
                        mOnItemLongClicked.onItemLongClick(ListViewHorizontal.this, child, mLeftViewIndex + 1 + i, mAdapter.getItemId(mLeftViewIndex + 1 + i));
                    }
                    break;
                }

            }
        }

        private boolean isEventWithinView(MotionEvent e, View child) {
            Rect viewRect = new Rect();
            int[] childPosition = new int[2];
            child.getLocationOnScreen(childPosition);
            int left = childPosition[0];
            int right = left + child.getWidth();
            int top = childPosition[1];
            int bottom = top + child.getHeight();
            viewRect.set(left, top, right, bottom);
            return viewRect.contains((int) e.getRawX(), (int) e.getRawY());
        }
    };

}

  1. en tu archivo XML:

<nombre.paquete.ListViewHorizontal
        android:id="@+id/lvHorizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.