效果图
代码
首先我们看布局文件
布局文件很简单,主要就是使用了一个StackView,这里我们给它加了一个属性loopViews为true,表示可以循环滑动。
Java代码
public classMainActivityextendsAppCompatActivity{ private StackView stackView;
private int[] imageIds = {R.drawable.ym1,R.drawable.ym2,R.drawable.ym3,R.drawable.ym4};
private List images = new ArrayList<>();
private ImageAdapter imageAdapter;
private TextView textView;
private Timer down;
private Timer timerup;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
stackView = (StackView) findViewById(R.id.stackview);
textView = (TextView) findViewById(R.id.textview);
initData();
imageAdapter = new ImageAdapter(images, this);
stackView.setAdapter(imageAdapter);
stackView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override public void onItemClick(AdapterView parent, View view, int position, long id) {
textView.setText("第"+(position+1)+"个杨幂");
}
});
}
public void initData(){
for (int i = 0; i < imageIds.length; i++) {
images.add(imageIds[i]);
}
}
public void click(View view){
switch (view.getId()){
case R.id.btn_down:
if(timerup!=null){
timerup.cancel();
}
down = new Timer();
down.schedule(new TimerTask() {
@Override public void run() {
runOnUiThread(new Runnable() {
@Override public void run() {
stackView.showNext();
}
});
}
},0,1000);
break;
case R.id.btn_up:
if(down!=null){
down.cancel();
}
timerup = new Timer();
timerup.schedule(new TimerTask() {
@Override public void run() {
runOnUiThread(new Runnable() {
@Override public void run() {
stackView.showPrevious();
}
});
}
},0,1000);
break;
}
}
}
给StackView设置了一个ImageAdapter
public classImageAdapterextendsBaseAdapter{ private List mImages;
private Context mContext;
public ImageAdapter(List mImages,Context context){
this.mImages = mImages;
mContext = context;
}
@Override public int getCount() {
return mImages.size();
}
@Override public Object getItem(int position) {
return mImages.get(position);
}
@Override public long getItemId(int position) {
return position;
}
@Override public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(mImages.get(position));
return imageView;
}
}