標籤:android的imageswitcher和textswitcher
ImageSwitcher:
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.imageswitch.MainActivity" > <ImageSwitcher android:id="@+id/imageSwitcher1_1" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentTop="true" > </ImageSwitcher></RelativeLayout><!-- android:inAnimation="@android:anim/slide_in_left" android:outAnimation="@android:anim/slide_out_right" -->
MianActivity
package com.example.imageswitch;import android.app.Activity;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.view.MotionEvent;import android.view.View;import android.view.View.OnTouchListener;import android.widget.ImageSwitcher;import android.widget.ImageView;import android.widget.ViewSwitcher.ViewFactory;public class MainActivity extends Activity implements ViewFactory ,OnTouchListener{private ImageSwitcher imageSwitch;private int [] images={R.drawable.kobe0,R.drawable.kobe1,R.drawable.kobe3,R.drawable.kobe4,R.drawable.kobe6,};private int index; //要顯示的圖片的下標@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);imageSwitch=(ImageSwitcher) findViewById(R.id.imageSwitcher1_1);//設定建立ImageView的工廠imageSwitch.setFactory(this);//設定觸屏事件imageSwitch.setOnTouchListener(this);}//ViewFactory工廠介面的方法,通過這個方法,給ImageSwitch組件提供兩個@Overridepublic View makeView() {// TODO Auto-generated method stubImageView imageView=new ImageView(this);imageView.setImageResource(images[0]);return imageView;}//定義兩個x座標點 float startx=0.0F; //開始位置 float endx=0.0F; //結束位置//觸屏事件監聽方法@Overridepublic boolean onTouch(View v, MotionEvent event) {if(event.getAction()==MotionEvent.ACTION_DOWN){startx=event.getX();return true;}else if(event.getAction()==MotionEvent.ACTION_UP){endx=event.getX();//判斷左滑動if(startx-endx>20){index=(index+1)<(images.length-1)?++index:0;imageSwitch.setImageResource(images[index]);//在代碼中設定動畫效果imageSwitch.setInAnimation(this, android.R.anim.fade_in);imageSwitch.setOutAnimation(this, android.R.anim.fade_out);}//判斷右滑動if(endx-startx>20){index=(index-1)>0?--index:images.length-1;imageSwitch.setImageResource(images[index]);imageSwitch.setInAnimation(this, android.R.anim.slide_in_left);imageSwitch.setOutAnimation(this, android.R.anim.slide_out_right);}}return true;}}
TextSwitcher與ImageSwitcher類似,只需要將ImageSwitcher換成TextSwitcher
設定圖片資源修改為設定文本即可
本文出自 “matengbing” 部落格,請務必保留此出處http://matengbing.blog.51cto.com/11395502/1882816
android的ImageSwitcher和TextSwitcher