Programing

Android에서 가로 ListView를 만들려면 어떻게해야합니까?

lottogame 2020. 5. 18. 08:05
반응형

Android에서 가로 ListView를 만들려면 어떻게해야합니까? [복제]


가능한 중복 :
안드로이드에서 가로 ListView?

안드로이드의 많은 것들처럼, 당신은 이것이 어려운 문제라고 생각하지 않을 것입니다. 그러나 어리석게도, 당신은 틀릴 것입니다. 그리고 안드로이드의 많은 것들과 마찬가지로 API는 확장 가능한 출발점을 제공하지도 않습니다. 내가 원하는 것은 물건을 가져 와서 옆으로 돌리는 것입니다. 내 자신의 ListView를 굴릴 경우 저주받을 것입니다. \ rant

자, 이제 연기를 마쳤으므로 문제 자체에 대해 이야기 해 봅시다. 내가 필요한 것은 기본적으로 정확히 Gallery이지만 센터 잠금 기능이없는 것입니다. 나는 실제로 ListViewlistSelector 가 필요하지 않지만 좋은 것입니다. 대부분 LinearLayout내부에서 원하는 것을 수행 할 수는 ScrollView있지만 a에서 가져온 자식 뷰가 필요하며 ListAdapter실제로 뷰 리사이클 러를 원합니다. 그리고 나는 정말 어떤 레이아웃 코드를 작성하고 싶지 않아요.

이 클래스 중 일부에 대한 소스 코드를 들여다 보았습니다 ...

갤러리 : 대부분의 'onXyz'메소드를 무시하고 모든 소스 코드를 복사하지만 호출하지 않는 경우 갤러리를 사용할 수있는 것 같습니다 scrollIntoSlots(). 그러나 그렇게하면 액세스 할 수없는 멤버 필드 또는 예기치 않은 결과가 발생할 수 있습니다.

AbsSpinner는 : 때문에 mRecycler필드가 패키지 비공개 나는이 클래스를 확장 할 수 있습니다 의심한다.

AbsListView : 이 클래스는 세로 스크롤 전용이므로 도움말이 없습니다.

AdapterView : 이 클래스를 직접 확장 할 필요는 없습니다. 당신이 나에게 쉬운 일이고 내 자신의 것을 굴리는 것이 쉽다고 말하면 RecycleBin, 나는 매우 회의적이지만 샷을 줄 것입니다.

나는 아마도 복사 할 수 가정 모두 AbsSpinnerGallery내가 잘하면 그 클래스가 나는 액세스 할 수 없습니다 일부 패키지 개인 변수를 사용하지 않는 ... 원하는 것을 얻을 수 있습니다. 여러분은 그것이 좋은 습관이라고 생각합니까? 누구든지 올바른 방향으로 안내 할 수있는 자습서 또는 타사 솔루션이 있습니까?

업데이트 :
지금까지 내가 찾은 유일한 해결책은 직접 수행하는 것입니다. 이 질문 AdapterView을 한 후 처음부터 자신의 "HorizontalListView"를 재정의 하고 구현했습니다. 갤러리의 중앙 잠금 기능을 실제로 재정의하는 유일한 방법은 개인 scrollIntoSlots메서드 를 재정의하는 것입니다. 개인 메서드는 런타임에 하위 클래스를 생성해야한다고 생각합니다. 당신이 그렇게 대담하다면, 아마도 최선의 해결책이지만, 나는 문서화되지 않은 메소드에 의존하고 싶지 않을 것입니다.

Swathi EP 아래 나는 줄 것을 제안 GalleryOnTouchListener스크롤 기능을 대체합니다. 당신이 가진 목록에 지원 날뛰는, 또는 뷰가 날뛰는 애니메이션의 끝에서 중심에 스냅하는 것이 괜찮아 경우, 다음이 걱정하지 않는 경우 것입니다 당신을 위해 작동! 그러나 결국 플링 지지대를 제거하지 않고 센터 잠금 기능을 제거하는 것은 여전히 ​​불가능합니다. 그리고 나는 당신에게 묻습니다. 어떤 종류의 목록이 도망 치지 않습니까?

아아, 이것은 나를 위해 작동하지 않았다. :-( 그러나이 접근법에 관심이 있다면 계속 읽어보십시오.

또한 Swathi의 코드를 추가하여 원하는 것을 얻었습니다. 에서가 GestureListener.onTouch, 제스처 검출기에 위임뿐만 아니라, 또한 true를 돌려했다 ACTION_UPACTION_CANCEL이벤트. 이는 중앙 잠금 기능을 성공적으로 비활성화했지만 플 링킹도 비활성화했습니다. 내 GestureListener 대리자에게 갤러리의 onFling메서드를 위임하여 플링을 다시 활성화 할 수있었습니다 . 시험해 보려면 ApiDemos 샘플 코드로 이동하여 Gallery1.java 클래스를 다음 코드로 바꾸십시오.

import com.example.android.apis.R;

import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.GestureDetector;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;

public class Gallery1 extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gallery_1);

        // Reference the Gallery view
        final Gallery g = (Gallery) findViewById(R.id.gallery);

        // Set the adapter to our custom adapter (below)
        g.setAdapter(new ImageAdapter(this));

        // Set a item click listener, and just Toast the clicked position
        g.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView parent, View v, int position, long id) {
                Toast.makeText(Gallery1.this, "" + position, Toast.LENGTH_SHORT).show();
            }
        });

        // Gesture detection
        final GestureDetector gestureDetector = new GestureDetector(new MyGestureDetector(g));
        OnTouchListener gestureListener = new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                boolean retVal = gestureDetector.onTouchEvent(event);
                int action = event.getAction();
                if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
                    retVal = true;
                    onUp();
                }
                return retVal;
            }

            public void onUp() {
                // Here I am merely copying the Gallery's onUp() method.
                for (int i = g.getChildCount() - 1; i >= 0; i--) {
                    g.getChildAt(i).setPressed(false);
                }
                g.setPressed(false);
            }
        };
        g.setOnTouchListener(gestureListener);

        // We also want to show context menu for longpressed items in the gallery
        registerForContextMenu(g);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        menu.add(R.string.gallery_2_text);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        Toast.makeText(this, "Longpress: " + info.position, Toast.LENGTH_SHORT).show();
        return true;
    }

    public class ImageAdapter extends BaseAdapter {
        int mGalleryItemBackground;

        public ImageAdapter(Context c) {
            mContext = c;
            // See res/values/attrs.xml for the <declare-styleable> that defines
            // Gallery1.
            TypedArray a = obtainStyledAttributes(R.styleable.Gallery1);
            mGalleryItemBackground = a.getResourceId(
                    R.styleable.Gallery1_android_galleryItemBackground, 0);
            a.recycle();
        }

        public int getCount() {
            return mImageIds.length;
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView i = new ImageView(mContext);

            i.setImageResource(mImageIds[position]);
            i.setScaleType(ImageView.ScaleType.FIT_XY);
            i.setLayoutParams(new Gallery.LayoutParams(136, 88));

            // The preferred Gallery item background
            i.setBackgroundResource(mGalleryItemBackground);

            return i;
        }

        private Context mContext;

        private Integer[] mImageIds = {
                R.drawable.gallery_photo_1,
                R.drawable.gallery_photo_2,
                R.drawable.gallery_photo_3,
                R.drawable.gallery_photo_4,
                R.drawable.gallery_photo_5,
                R.drawable.gallery_photo_6,
                R.drawable.gallery_photo_7,
                R.drawable.gallery_photo_8
        };
    }

    public class MyGestureDetector extends SimpleOnGestureListener {

        private Gallery gallery;

        public MyGestureDetector(Gallery gallery) {
            this.gallery = gallery;
        }

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

}

이 게시물을 읽은 후 내 수평을 구현했습니다 ListView. 여기에서 찾을 수 있습니다 : http://dev-smart.com/horizontal-listview/ 이것이 도움이되는지 알려주십시오.


Have you looked into using a HorizontalScrollView to wrap your list items? That will allow each of your list items to be horizontally scrollable (what you put in there is up to you, and can make them dynamic items similar to ListView). This will work well if you are only after a single row of items.


You know, it might be possible to use an existing ListView with some judicious overriding of dispatchDraw() (to rotate the Canvas by 90 degrees), onTouch() (to swap the X and Y of the MotionEvent coords) and maybe onMeasure() or whatever to fool it into thinking it's y by x rather than x by y...

I have no idea if this would actually work but it'd be fun to find out. :)


This might be a very late reply but it is working for us. We are using the same gallery provided by Android, just that, we have adjusted the left margin such a way that the screens left end is considered as Gallery's center. That really worked well for us.


I used Pauls (see his answer) Implementation of HorizontalListview and it works, thank you so much for sharing!

I slightly changed his HorizontalListView-Class (btw. Paul there is a typo in your classname, your classname is "HorizontialListView" instead of "HorizontalListView", the "i" is too much) to update child-views when selected.

UPDATE: My code that I posted here was wrong I suppose, as I ran into trouble with selection (i think it has to do with view recycling), I have to go back to the drawing board...

UPDATE 2: Ok Problem solved, I simply commented "removeNonVisibleItems(dx);" in "onLayout(..)", I guess this will hurt performance, but since I am using only very small Lists this is no Problem for me.

I basically used this tutorial here on developerlife and just replaced ListView with Pauls HorizontalListView, and made the changes to allow for "permanent" selection (a child that is clicked on changes its appearance, and when its clicked on again it changes it back).

I am a beginner, so probably many ugly things in the code, let me know if you need more details.


Gallery is the best solution, i have tried it. I was working on one mail app, in which mails in the inbox where displayed as listview, i wanted an horizontal view, i just converted listview to gallery and everything worked fine as i needed without any errors. For the scroll effect i enabled gesture listener for the gallery. I hope this answer may help u.


Have you looked into the ViewFlipper component? Maybe it can help you.

http://developer.android.com/reference/android/widget/ViewFlipper.html

With this component, you can attach two or more view childs. If you add some translate animation and capture Gesture detection, you can have a nicely horizontal scroll.


My app uses a ListView in portraint mode which is simply switches to Gallery in landscape mode. Both of them use one BaseAdapter. This looks like shown below.

       setContentView(R.layout.somelayout);
       orientation = getResources().getConfiguration().orientation;

       if ( orientation == Configuration.ORIENTATION_LANDSCAPE )
       {

            Gallery gallery = (Gallery)findViewById( R.id.somegallery );

            gallery.setAdapter( someAdapter );

            gallery.setOnItemClickListener( new OnItemClickListener() {
            @Override
            public void onItemClick( AdapterView<?> parent, View view,
                    int position, long id ) {

                onClick( position );
            }
        });
       }
       else
       {
            setListAdapter( someAdapter );

            getListView().setOnScrollListener(this);
       }    

To handle scrolling events I've inherited my own widget from Gallery and override onFling(). Here's the layout.xml:

    <view 
    class="package$somegallery"
    android:id="@+id/somegallery" 
    android:layout_height="fill_parent" 
    android:layout_width="fill_parent">
    </view>

and code:

    public static class somegallery extends Gallery
    {
        private Context mCtx;

        public somegallery(Context context, AttributeSet attrs)
        {
            super(context, attrs);
            mCtx = context;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                float velocityY) {

            ( (CurrentActivity)mCtx ).onScroll();

            return super.onFling(e1, e2, velocityX, velocityY);
        }
   }

참고URL : https://stackoverflow.com/questions/3877040/how-can-i-make-a-horizontal-listview-in-android

반응형