Horizontal ListView in Android?

后端 未结 19 1285
深忆病人
深忆病人 2020-11-22 03:54

Is it possible to make the ListView horizontally? I have done this using a gallery view, but the selected item comes to the center of the screen automatically.

19条回答
  •  暖寄归人
    2020-11-22 04:26

    My solution is to simply use ViewPager widget. It isn't center-locked as Gallery and has a built-in features for recycling views (as ListView). You may see similar approach at Google Play app, whenever you deal with horizontally scrollable lists.

    You just need to extend PagerAdapter and perform a couple of tweaks there:

    public class MyPagerAdapter extends PagerAdapter {
    
        private Context mContext;
    
        public MyPagerAdapter(Context context) {
            this.mContext = context;
        }
    
        // As per docs, you may use views as key objects directly 
        // if they aren't too complex
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            LayoutInflater inflater = LayoutInflater.from(mContext);
            View view = inflater.inflate(R.layout.item, null);
            container.addView(view);
            return view;
        }
    
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    
        @Override
        public int getCount() {
            return 10;
        }
    
        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
    
        // Important: page takes all available width by default,
        // so let's override this method to fit 5 pages within single screen
        @Override
        public float getPageWidth(int position) {
            return 0.2f;
        }
    }
    

    As result, you'll have horizontally scrollable widget with adapter, like this: enter image description here

提交回复
热议问题