主要为了记录自己的学习成果,复盘学习的内容,免得第二天自己写了什么都忘了。
今天主要做了一个ViewPager的demo,写了一个适配器。
public class ImagePagerAdapter extends PagerAdapter { private Context mContent; private ArrayList<ImageView> mViewList=new ArrayList<ImageView>(); private ArrayList<GoodsInfo> mGoodsList=new ArrayList<GoodsInfo>(); public ImagePagerAdapter(Context mContent, ArrayList<GoodsInfo> mGoodsList) { this.mContent = mContent; this.mGoodsList = mGoodsList; for(int i=0;i<mGoodsList.size();i++){ ImageView view=new ImageView(mContent); view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); view.setImageResource(mGoodsList.get(i).pic); view.setScaleType(ImageView.ScaleType.FIT_CENTER); mViewList.add(view); } } @Override public int getCount() { return mViewList.size(); } @Override public boolean isViewFromObject(View view, Object object) { return view==object; } @Override
public void destroyItem(ViewGroup container, int position, Object object) { container.removeView(mViewList.get(position)); } @Override public Object instantiateItem(ViewGroup container, int position) { container.addView(mViewList.get(position)); return mViewList.get(position); } }
1,主要注意setLayoutParams的写法。
在Activity下加载,写一个监听事件。
public class MainActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener { private ArrayList<GoodsInfo> mgoodsList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ViewPager vp_content=findViewById(R.id.vp_content); mgoodsList=GoodsInfo.getDefaultList(); ImagePagerAdapter adapter=new ImagePagerAdapter(this,mgoodsList); vp_content.setAdapter(adapter); vp_content.setCurrentItem(0); vp_content.addOnPageChangeListener(this); } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { Toast.makeText(this,"你选择的手机是"+mgoodsList.get(position).name,Toast.LENGTH_SHORT).show(); } @Override public void onPageScrollStateChanged(int state) { } }
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦