web-dev-qa-db-fra.com

Comment implémenter HorizontalScrollView comme Gallery?

Je veux implémenter Horizontal ScrollView avec certaines fonctionnalités de Gallery, enter image description here

Dans Galerie, le défilement effectué à une certaine distance s’organise par paire, c’est-à-dire que si nous avons trois images affichées à l’écran, un clic sur la dernière image permet d’organiser le défilement au centre.

Comment pourrais-je implémenter HorizontalSCrollView comme mentionné?

69
Jayesh

Essayez ce code:

activity_main.xml

<RelativeLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
xmlns:tools="http://schemas.Android.com/tools"
Android:layout_width="fill_parent"
Android:layout_height="100dip"
tools:context=".MainActivity" >
<HorizontalScrollView
    Android:id="@+id/hsv"
    Android:layout_width="fill_parent"
    Android:layout_height="wrap_content"
    Android:layout_alignParentTop="true"
    Android:fillViewport="true"
    Android:measureAllChildren="false"
    Android:scrollbars="none" >
    <LinearLayout
        Android:id="@+id/innerLay"
        Android:layout_width="wrap_content"
        Android:layout_height="wrap_content"
        Android:gravity="center_vertical"
        Android:orientation="horizontal" >
        <LinearLayout
            Android:id="@+id/asthma_action_plan"
            Android:layout_width="wrap_content"
            Android:layout_height="wrap_content"
            Android:gravity="center"
            Android:orientation="vertical" >
            <RelativeLayout
                Android:layout_width="fill_parent"
                Android:layout_height="match_parent" >
                <ImageView
                    Android:layout_width="wrap_content"
                    Android:layout_height="wrap_content"
                    Android:src="@drawable/action_plan" />
                <TextView
                    Android:layout_width="0.2dp"
                    Android:layout_height="fill_parent"
                    Android:layout_alignParentRight="true"
                    Android:background="@drawable/ln" />
            </RelativeLayout>
        </LinearLayout>
        <LinearLayout
            Android:id="@+id/controlled_medication"
            Android:layout_width="wrap_content"
            Android:layout_height="wrap_content"
            Android:gravity="center"
            Android:orientation="vertical" >
            <RelativeLayout
                Android:layout_width="fill_parent"
                Android:layout_height="match_parent" >
                <ImageView
                    Android:layout_width="wrap_content"
                    Android:layout_height="wrap_content"
                    Android:src="@drawable/controlled" />
                <TextView
                    Android:layout_width="0.2dp"
                    Android:layout_height="fill_parent"
                    Android:layout_alignParentRight="true"
                    Android:background="@drawable/ln" />
            </RelativeLayout>
        </LinearLayout>
        <LinearLayout
            Android:id="@+id/as_needed_medication"
            Android:layout_width="wrap_content"
            Android:layout_height="wrap_content"
            Android:gravity="center"
            Android:orientation="vertical" >
            <RelativeLayout
                Android:layout_width="fill_parent"
                Android:layout_height="match_parent"
                Android:orientation="horizontal" >
                <ImageView
                    Android:layout_width="wrap_content"
                    Android:layout_height="wrap_content"
                    Android:src="@drawable/as_needed" />
                <TextView
                    Android:layout_width="0.2dp"
                    Android:layout_height="fill_parent"
                    Android:layout_alignParentRight="true"
                    Android:background="@drawable/ln" />
            </RelativeLayout>
        </LinearLayout>
        <LinearLayout
            Android:id="@+id/rescue_medication"
            Android:layout_width="wrap_content"
            Android:layout_height="wrap_content"
            Android:gravity="center"
            Android:orientation="vertical" >
            <RelativeLayout
                Android:layout_width="fill_parent"
                Android:layout_height="match_parent" >
                <ImageView
                    Android:layout_width="wrap_content"
                    Android:layout_height="wrap_content"
                    Android:src="@drawable/rescue" />
                <TextView
                    Android:layout_width="0.2dp"
                    Android:layout_height="fill_parent"
                    Android:layout_alignParentRight="true"
                    Android:background="@drawable/ln" />
            </RelativeLayout>
        </LinearLayout>
        <LinearLayout
            Android:id="@+id/your_symptoms"
            Android:layout_width="wrap_content"
            Android:layout_height="wrap_content"
            Android:gravity="center"
            Android:orientation="vertical" >
            <RelativeLayout
                Android:layout_width="fill_parent"
                Android:layout_height="match_parent" >
                <ImageView
                    Android:layout_width="wrap_content"
                    Android:layout_height="wrap_content"
                    Android:src="@drawable/symptoms" />
                <TextView
                    Android:layout_width="0.2dp"
                    Android:layout_height="fill_parent"
                    Android:layout_alignParentRight="true"
                    Android:background="@drawable/ln" />
            </RelativeLayout>
        </LinearLayout>
        <LinearLayout
            Android:id="@+id/your_triggers"
            Android:layout_width="wrap_content"
            Android:layout_height="wrap_content"
            Android:gravity="center"
            Android:orientation="vertical" >
            <RelativeLayout
                Android:layout_width="fill_parent"
                Android:layout_height="match_parent" >
                <ImageView
                    Android:layout_width="wrap_content"
                    Android:layout_height="wrap_content"
                    Android:src="@drawable/triggers" />
                <TextView
                    Android:layout_width="0.2dp"
                    Android:layout_height="fill_parent"
                    Android:layout_alignParentRight="true"
                    Android:background="@drawable/ln" />
            </RelativeLayout>
        </LinearLayout>
        <LinearLayout
            Android:id="@+id/wheeze_rate"
            Android:layout_width="wrap_content"
            Android:layout_height="wrap_content"
            Android:gravity="center"
            Android:orientation="vertical" >
            <RelativeLayout
                Android:layout_width="fill_parent"
                Android:layout_height="match_parent" >
                <ImageView
                    Android:layout_width="wrap_content"
                    Android:layout_height="wrap_content"
                    Android:src="@drawable/wheeze_rate" />
                <TextView
                    Android:layout_width="0.2dp"
                    Android:layout_height="fill_parent"
                    Android:layout_alignParentRight="true"
                    Android:background="@drawable/ln" />
            </RelativeLayout>
        </LinearLayout>
        <LinearLayout
            Android:id="@+id/peak_flow"
            Android:layout_width="wrap_content"
            Android:layout_height="wrap_content"
            Android:gravity="center"
            Android:orientation="vertical" >
            <RelativeLayout
                Android:layout_width="fill_parent"
                Android:layout_height="match_parent" >
                <ImageView
                    Android:layout_width="wrap_content"
                    Android:layout_height="wrap_content"
                    Android:src="@drawable/peak_flow" />
                <TextView
                    Android:layout_width="0.2dp"
                    Android:layout_height="fill_parent"
                    Android:layout_alignParentRight="true"
                    Android:background="@drawable/ln" />
            </RelativeLayout>
        </LinearLayout>
    </LinearLayout>
</HorizontalScrollView>
<TextView
    Android:layout_width="fill_parent"
    Android:layout_height="0.2dp"
    Android:layout_alignParentRight="true"
    Android:layout_below="@+id/hsv"
    Android:background="@drawable/ln" />
<LinearLayout
    Android:id="@+id/prev"
    Android:layout_width="wrap_content"
    Android:layout_height="fill_parent"
    Android:layout_alignParentLeft="true"
    Android:layout_centerVertical="true"
    Android:paddingLeft="5dip"
    Android:paddingRight="5dip"
    Android:descendantFocusability="blocksDescendants" >
    <ImageView
        Android:layout_width="wrap_content"
        Android:layout_height="wrap_content"
        Android:layout_gravity="center_vertical"
        Android:src="@drawable/prev_arrow" />
</LinearLayout>
<LinearLayout
    Android:id="@+id/next"
    Android:layout_width="wrap_content"
    Android:layout_height="fill_parent"
    Android:layout_alignParentRight="true"
    Android:layout_centerVertical="true"
    Android:paddingLeft="5dip"
    Android:paddingRight="5dip"
    Android:descendantFocusability="blocksDescendants" >
    <ImageView
        Android:layout_width="wrap_content"
        Android:layout_height="wrap_content"
        Android:layout_gravity="center_vertical"
        Android:src="@drawable/next_arrow" />
</LinearLayout>
</RelativeLayout>

grid_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
Android:layout_width="match_parent"
Android:layout_height="match_parent"
Android:orientation="vertical" >
<ImageView
    Android:id="@+id/imageView1"
    Android:layout_width="fill_parent"
    Android:layout_height="100dp"
    Android:src="@drawable/ic_launcher" />
</LinearLayout>

MainActivity.Java

import Java.util.ArrayList;

import Android.app.Activity;
import Android.graphics.Rect;
import Android.os.Bundle;
import Android.os.Handler;
import Android.view.Display;
import Android.view.GestureDetector;
import Android.view.GestureDetector.SimpleOnGestureListener;
import Android.view.MotionEvent;
import Android.view.View;
import Android.view.View.OnTouchListener;
import Android.widget.HorizontalScrollView;
import Android.widget.LinearLayout;
import Android.widget.LinearLayout.LayoutParams;

public class MainActivity extends Activity {

LinearLayout asthmaActionPlan, controlledMedication, asNeededMedication,
        rescueMedication, yourSymtoms, yourTriggers, wheezeRate, peakFlow;
LayoutParams params;
LinearLayout next, prev;
int viewWidth;
GestureDetector gestureDetector = null;
HorizontalScrollView horizontalScrollView;
ArrayList<LinearLayout> layouts;
int parentLeft, parentRight;
int mWidth;
int currPosition, prevPosition;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    prev = (LinearLayout) findViewById(R.id.prev);
    next = (LinearLayout) findViewById(R.id.next);
    horizontalScrollView = (HorizontalScrollView) findViewById(R.id.hsv);
    gestureDetector = new GestureDetector(new MyGestureDetector());
    asthmaActionPlan = (LinearLayout) findViewById(R.id.asthma_action_plan);
    controlledMedication = (LinearLayout) findViewById(R.id.controlled_medication);
    asNeededMedication = (LinearLayout) findViewById(R.id.as_needed_medication);
    rescueMedication = (LinearLayout) findViewById(R.id.rescue_medication);
    yourSymtoms = (LinearLayout) findViewById(R.id.your_symptoms);
    yourTriggers = (LinearLayout) findViewById(R.id.your_triggers);
    wheezeRate = (LinearLayout) findViewById(R.id.wheeze_rate);
    peakFlow = (LinearLayout) findViewById(R.id.peak_flow);

    Display display = getWindowManager().getDefaultDisplay();
    mWidth = display.getWidth(); // deprecated
    viewWidth = mWidth / 3;
    layouts = new ArrayList<LinearLayout>();
    params = new LayoutParams(viewWidth, LayoutParams.WRAP_CONTENT);

    asthmaActionPlan.setLayoutParams(params);
    controlledMedication.setLayoutParams(params);
    asNeededMedication.setLayoutParams(params);
    rescueMedication.setLayoutParams(params);
    yourSymtoms.setLayoutParams(params);
    yourTriggers.setLayoutParams(params);
    wheezeRate.setLayoutParams(params);
    peakFlow.setLayoutParams(params);

    layouts.add(asthmaActionPlan);
    layouts.add(controlledMedication);
    layouts.add(asNeededMedication);
    layouts.add(rescueMedication);
    layouts.add(yourSymtoms);
    layouts.add(yourTriggers);
    layouts.add(wheezeRate);
    layouts.add(peakFlow);

    next.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    horizontalScrollView.smoothScrollTo(
                            (int) horizontalScrollView.getScrollX()
                                    + viewWidth,
                            (int) horizontalScrollView.getScrollY());
                }
            }, 100L);
        }
    });

    prev.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    horizontalScrollView.smoothScrollTo(
                            (int) horizontalScrollView.getScrollX()
                                    - viewWidth,
                            (int) horizontalScrollView.getScrollY());
                }
            }, 100L);
        }
    });

    horizontalScrollView.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (gestureDetector.onTouchEvent(event)) {
                return true;
            }
            return false;
        }
    });
}

class MyGestureDetector extends SimpleOnGestureListener {
    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
            float velocityY) {
        if (e1.getX() < e2.getX()) {
            currPosition = getVisibleViews("left");
        } else {
            currPosition = getVisibleViews("right");
        }

        horizontalScrollView.smoothScrollTo(layouts.get(currPosition)
                .getLeft(), 0);
        return true;
    }
}

public int getVisibleViews(String direction) {
    Rect hitRect = new Rect();
    int position = 0;
    int rightCounter = 0;
    for (int i = 0; i < layouts.size(); i++) {
        if (layouts.get(i).getLocalVisibleRect(hitRect)) {
            if (direction.equals("left")) {
                position = i;
                break;
            } else if (direction.equals("right")) {
                rightCounter++;
                position = i;
                if (rightCounter == 2)
                    break;
            }
        }
    }
    return position;
}
}

Faites-moi savoir si tout problème profiter ...

93
Vijju

Voici ma mise en page:

    <HorizontalScrollView
        Android:id="@+id/horizontalScrollView1"
        Android:layout_width="wrap_content"
        Android:layout_height="wrap_content"
        Android:paddingTop="@dimen/padding" >

       <LinearLayout
        Android:id="@+id/shapeLayout"
        Android:layout_width="fill_parent"
        Android:layout_height="wrap_content"
        Android:layout_marginTop="10dp" >
        </LinearLayout>
    </HorizontalScrollView>

Et je le renseigne dans le code avec des cases à cocher dynamiques.

22
Gil Allen

Ici est un bon tutoriel avec du code. Dites-moi si cela marche pour vous! This est également un bon tutoriel.

EDIT

Dans This exemple, tout ce que vous avez à faire est d’ajouter cette ligne:

gallery.setSelection(1);

après avoir défini l'adaptateur sur l'objet gallery, la ligne est la suivante:

gallery.setAdapter(new ImageAdapter(this));

UPDATE1

Ok, j'ai ton problème. This bibliothèque open source est votre solution. Je l'ai également utilisé pour l'un de mes projets. J'espère que cela résoudra votre problème enfin.

UPDATE2:

Je vous suggère de passer par ceci tutoriel . Vous pourriez avoir une idée. Je pense que j'ai eu votre problème, vous voulez le scrollview horizontal avec snap . Essayez de chercher avec ce mot clé sur google ou ici, vous pourriez obtenir votre solution.

2
user3513843

J'ai mis en œuvre quelque chose de similaire avec Horizontal Variable ListView Le seul inconvénient est que cela fonctionne uniquement avec Android 2.3 et versions ultérieures.

Utiliser cette bibliothèque est aussi simple que d’implémenter un ListView avec un adaptateur correspondant. La bibliothèque fournit également un exemple

0
andreasg

J'ai créé une liste horizontale ListView dans chaque ligne de ListView si vous le souhaitez single Vous pouvez faire ce qui suit

Ici, je viens de créer horizontalListView de miniatures de vidéos similaires

enter image description here

L'idée est simplement d'ajouter continuellement ImageView à l'enfant de LinearLayout dans HorizontalscrollView

Remarque: n'oubliez pas de déclencher . RemoveAllViews (); avant le prochain chargement autrement, il va ajouter un enfant en double

Cursor mImageCursor = db.getPlaylistVideoImage(playlistId);
mVideosThumbs.removeAllViews();
if (mImageCursor != null && mImageCursor.getCount() > 0) {
    for (int index = 0; index < mImageCursor.getCount(); index++) {
        mImageCursor.moveToPosition(index);
        ImageView iv = (ImageView) imageViewInfalter.inflate(
            R.layout.image_view, null);
                    name = mImageCursor.getString(mImageCursor
                    .getColumnIndex("LogoDefaultName"));
        logoFile = new File(MyApplication.LOCAL_LOGO_PATH, name);
                    if (logoFile.exists()) {    
                Uri uri = Uri.fromFile(logoFile);
                iv.setImageURI(uri);                    
            }
            iv.setScaleType(ScaleType.FIT_XY);
            mVideosThumbs.addView(iv);
    }
    mImageCursor.close();
    mImageCursor = null;
    } else {
        ImageView iv = (ImageView) imageViewInfalter.inflate(
                    R.layout.image_view, null);
        String name = "";
        File logoFile;
        name = mImageCursor.getString(mImageCursor
                    .getColumnIndex("LogoMediumName"));
        logoFile = new File(MyApplication.LOCAL_LOGO_PATH, name);
        if (logoFile.exists()) {
            Uri uri = Uri.fromFile(logoFile);
            iv.setImageURI(uri);
            }
        }

Mon xml pour HorizontalListView

<HorizontalScrollView
    Android:id="@+id/horizontalScrollView"
    Android:layout_width="fill_parent"
    Android:layout_height="wrap_content"
    Android:layout_alignParentLeft="true"
    Android:layout_below="@+id/linearLayoutTitle"
    Android:background="@drawable/shelf"
    Android:paddingBottom="@dimen/Playlist_TopBottom_margin"
    Android:paddingLeft="@dimen/playlist_RightLeft_margin"
    Android:paddingRight="@dimen/playlist_RightLeft_margin"
    Android:paddingTop="@dimen/Playlist_TopBottom_margin" >

    <LinearLayout
        Android:id="@+id/linearLayoutVideos"
        Android:layout_width="wrap_content"
        Android:layout_height="wrap_content"
        Android:gravity="left|center_vertical"
        Android:orientation="horizontal" >
    </LinearLayout>
</HorizontalScrollView>

et aussi mon image Voir chaque enfant

<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:Android="http://schemas.Android.com/apk/res/Android"


  Android:id="@+id/imageViewThumb"
    Android:layout_width="wrap_content"
    Android:layout_height="wrap_content"
    Android:layout_gravity="center"
    Android:layout_marginRight="20dp"
    Android:adjustViewBounds="true"
    Android:background="@Android:color/transparent"
    Android:contentDescription="@string/action_settings"
    Android:cropToPadding="true"
    Android:maxHeight="200dp"
    Android:maxWidth="240dp"
    Android:padding="@dimen/playlist_image_padding"
    Android:scaleType="centerCrop"
    Android:src="@drawable/loading" />

Pour en savoir plus, vous pouvez suivre les liens suivants qui ont quelques exemples faciles

  1. http://www.dev-smart.com/?p=34
  2. liste horizontale dans Android?
0
Trikaldarshi

Vous pouvez utiliser HorizontalScrollView pour implémenter le défilement horizontal.

Code

<HorizontalScrollView
Android:id="@+id/hsv"
Android:layout_width="fill_parent"
Android:layout_height="100dp"
 Android:layout_weight="0"
Android:fillViewport="true"
Android:measureAllChildren="false"
Android:scrollbars="none" >
<LinearLayout
    Android:id="@+id/innerLay"
    Android:layout_width="wrap_content"
    Android:layout_height="100dp"
    Android:gravity="center_vertical"
    Android:orientation="horizontal" >
    </LinearLayout>
    </HorizontalScrollView>

sélectionnée.xml:

<?xml version="1.0" encoding="utf-8"?>
   <LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
  Android:layout_width="160dp"
   Android:layout_margin="4dp"
Android:layout_height="match_parent"
Android:orientation="vertical" >

      <RelativeLayout 
Android:layout_width="fill_parent"
Android:layout_height="fill_parent" 
>

<ProgressBar                
    Android:layout_width="15dip"       
    Android:layout_height="15dip"
    Android:id="@+id/progress" 
    Android:layout_centerInParent="true"
    />

<ImageView
    Android:id="@+id/image"       
    Android:layout_width="fill_parent"       
    Android:layout_height="fill_parent"
    Android:background="#20000000"
    />

<TextView
    Android:id="@+id/textView1"
    Android:layout_width="fill_parent"
    Android:layout_height="30dp"
    Android:layout_alignParentBottom="true"
    Android:layout_alignParentRight="true"
    Android:gravity="center"
    Android:textColor="#000000"
    Android:background="#ffffff"
    Android:text="Image Text" />

      </RelativeLayout>
     </LinearLayout>

Code Java:

 LayoutInflater inflater;

    inflater=getLayoutInflater();
    LinearLayout inLay=(LinearLayout) findViewById(R.id.innerLay);

    for(int x=0;x<10;x++)
    {
        inLay.addView(getView(x));
    }




 View getView(final int x)
{
   View rootView = inflater.inflate( R.layout.featured_item,null);

   ImageView image = (ImageView) rootView.findViewById(R.id.image);

   //Thease Two Line is sufficient my dear to implement lazyLoading
   AQuery aq = new AQuery(rootView);
   String url="http://farm6.static.flickr.com/5035/5802797131_a729dac808_s.jpg";
   aq.id(image).progress(R.id.progress).image(url, true, true, 0, R.drawable.placeholder1);
   image.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
     Toast.makeText(PhotoActivity.this, "Click Here Postion "+x,     

         Toast.LENGTH_LONG).show();
        }
    });
   return rootView;
       }

Remarque: pour implémenter le chargement différé, veuillez utiliser ce lien pour AQUERY.

https://code.google.com/p/Android-query/wiki/ImageLoading

0
Ashish Saini