ViewPage實現輪播圖

Qcw_As發表於2018-10-29

1.在fragment中寫點選事件,當點選圖片的時候讓它跳轉
Intent intent = new Intent(getContext(), Main3Activity.class);
intent.putExtra(“position”,position);
intent.putStringArrayListExtra(“list”,ls);
startActivity(intent);

2.在MainActivity中獲取你傳過來的值
public class Main3Activity extends AppCompatActivity implements ViewPager.OnPageChangeListener {

private TextView tv;
private ViewPager viewpager;
private ArrayList<String> list;

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

private void initView() {
    tv = (TextView) findViewById(R.id.tv);
    viewpager = (ViewPager) findViewById(R.id.viewpager);

    Intent intent = getIntent();
    int position = intent.getIntExtra("position", 0);
    list = intent.getStringArrayListExtra("list");

    tv.setText(position+1+"/"+ list.size());

    ViewPagerAdatper adatper = new ViewPagerAdatper(this, list);
    viewpager.setAdapter(adatper);

    //viewpager預設顯示
    viewpager.setCurrentItem(position);
    //監聽事件
    viewpager.addOnPageChangeListener(this);
}

@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

}

@Override
public void onPageSelected(int position) {
    tv.setText(position+1+"/"+list.size());
}

@Override
public void onPageScrollStateChanged(int state) {

}

}
3.定義自己的介面卡ViewPagerAdatper繼承PagerAdapter
public class ViewPagerAdatper extends PagerAdapter {

private Context context;
private ArrayList<String> list;

public ViewPagerAdatper(Context context, ArrayList<String> list) {
    this.context = context;
    this.list = list;
}

@Override
public int getCount() {
    return list.size();
}

@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
    return view == object;
}

@Override
public Object instantiateItem(ViewGroup container, int position) {
    String url = list.get(position);
    ImageView photoView = new ImageView(context);
    Glide.with(context)
            .load("http:"+url)
            .into(photoView);
    //新增檢視
    container.addView(photoView);
    return photoView;
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    //移除檢視
    container.removeView((View) object);
}

}

相關文章