安卓進階組件-----映像切換器,安卓-----切換器
安卓映像切換器<ImageSwitch>是一種能夠實現映像序列播放的組件,類似於“windows相片檢視器”點擊左右按鈕實現按順序查看照片。ImageSwitch實際上是繼承了ViewSwitch,重寫了ViewSwitch的showNext() showprevious()兩個方法,這使得查看上下某張圖片變得十分簡單。
ImageSwitch提供了一個ViewFactory介面,ViewFactory產生的View組件必須是ImageView。進行圖片切換時,只要調用setImageResource(int resid) 方法更換圖片。
圖片切換器的實現:
1.建立工程,布局中放入ImageSwitch組件和兩個按鈕
<LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" > <ImageSwitcher android:id="@+id/imageSwitcher1" android:layout_weight="1" android:layout_gravity="center" android:layout_width="wrap_content" android:layout_height="wrap_content" > </ImageSwitcher> <LinearLayout android:layout_weight="1" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center_horizontal" android:orientation="horizontal" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="上一張" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="下一張" /> </LinearLayout> </LinearLayout>
2.在主活動建立一個映像id數組和映像切換器對象還有按鈕
private int[] image = new int[]{R.drawable.photo1,R.drawable.photo2, R.drawable.photo3,R.drawable.photo4}; //映像數組 private int index = 0; //下標 private ImageSwitcher is; //切換器
private Button up,down;
3.擷取組件執行個體化並設定ImageSwitch.setFactory()
is = (ImageSwitcher)findViewById(R.id.imageSwitcher1); up = (Button)findViewById(R.id.button1); down = (Button)findViewById(R.id.button2); up.setOnClickListener(this); down.setOnClickListener(this); is.setFactory(new ViewFactory() { @Override public View makeView() { ImageView imageView = new ImageView(MainActivity.this); imageView.setScaleType(ImageView.ScaleType.FIT_CENTER); return imageView; } }); is.setImageResource(image[index]); }
4.改按鈕加監聽,監聽介面在Activity實現。此處注意,監聽事件加上以後,擷取的是點擊的View組件id,通過switch判斷點擊的按鈕是上一張還是下一張的按鈕。
其實,監聽介面使用的是View的監聽介面,返回的對象是View,通過View.getId()擷取
up.setOnClickListener(this); down.setOnClickListener(this); public void onClick(View v) { switch(v.getId()){ case R.id.button1: if(index > 0){ index --; }else { index = image.length - 1; } is.setImageResource(image[index]);break; case R.id.button2: if(index == image.length - 1){ index = 0; }else { index ++; } is.setImageResource(image[index]);break; } }
運行效果:
總結:我們主Activity實現的View的介面, public void onClick(View v) {},在這個方法裡面我們隊v進行判斷,反應了安卓組件是繼承自View類。