用ViewFlipper與GestureDetector來(lái)實(shí)現(xiàn)圖片的左右滑動(dòng)效果。
創(chuàng)新互聯(lián)是網(wǎng)站建設(shè)專(zhuān)家,致力于互聯(lián)網(wǎng)品牌建設(shè)與網(wǎng)絡(luò)營(yíng)銷(xiāo),專(zhuān)業(yè)領(lǐng)域包括成都做網(wǎng)站、網(wǎng)站建設(shè)、電商網(wǎng)站制作開(kāi)發(fā)、微信平臺(tái)小程序開(kāi)發(fā)、微信營(yíng)銷(xiāo)、系統(tǒng)平臺(tái)開(kāi)發(fā),與其他網(wǎng)站設(shè)計(jì)及系統(tǒng)開(kāi)發(fā)公司不同,我們的整合解決方案結(jié)合了恒基網(wǎng)絡(luò)品牌建設(shè)經(jīng)驗(yàn)和互聯(lián)網(wǎng)整合營(yíng)銷(xiāo)的理念,并將策略和執(zhí)行緊密結(jié)合,且不斷評(píng)估并優(yōu)化我們的方案,為客戶(hù)提供全方位的互聯(lián)網(wǎng)品牌整合方案!
首先在布局xml中添加ViewFlipper控件:
在A(yíng)ctivity中實(shí)現(xiàn)GestureDetector的OnGestureListener監(jiān)聽(tīng):
mGesture = new GestureDetector(this, this);
public boolean onDown(MotionEvent e) { return false; } public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { return false; } public void onLongPress(MotionEvent e) { } public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { return false; } public void onShowPress(MotionEvent e) { } public boolean onSingleTapUp(MotionEvent e) { return false; }
為ViewFilpper加入View,如圖片、文字等:
mFilpper = (ViewFlipper) findViewById(R.id.flipper); mFilpper.addView(addImageView(R.drawable.chrysanthemum)); mFilpper.addView(addImageView(R.drawable.desert)); mFilpper.addView(addImageView(R.drawable.ic_launcher)); mFilpper.addView(addImageView(R.drawable.koala)); mFilpper.addView(addImageView(R.drawable.penguins)); mFilpper.addView(addImageView(R.drawable.lighthouse)); mFilpper.addView(addText("你好"));
public ImageView addImageView(int resId) { ImageView p_w_picpath = new ImageView(this); p_w_picpath.setImageResource(resId); return p_w_picpath; } private View addText(String string) { TextView textView = new TextView(this); textView.setText(string); return textView; }
在onFling()中編寫(xiě)滑動(dòng)效果:
@Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { Log.e("onFling", "onFling"); if (e1.getX() - e2.getX() > 120) { mFilpper.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.left_in)); mFilpper.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.left_out)); mFilpper.showPrevious(); } else if (e2.getX() - e1.getX() > 120) { mFilpper.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.rigth_in)); mFilpper.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.right_out)); mFilpper.showNext(); } return false; }
其中的left_in.xml如下:
left_out.xml:
right_in.xml:
right_out.xml:
最后還要重寫(xiě)onTouchEvent()方法在其中調(diào)用GestureDetector的onTouchEvent()方法:
@Override public boolean onTouchEvent(MotionEvent event) { Log.e("onTouchEvent", "onTouchEvent"); return mGesture.onTouchEvent(event); }