ImageSwitcher元件應用

ImageSwitcher 圖片切換器

我們可以看到很多網站首頁裏的有個圖片輪顯控制項,用來顯示站內重點新聞等,在
Android 裏也有這個ImageSwitcher 提供了類似的功能。那麼我們就做一個例子:

1. 準備好6 張圖片,放在res\drawable 目錄下:sakura01s.jpg~ sakura06s.jpg

2. helloswitcher.xml 中加入一個ImageSwitcher 元件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ImageSwitcher

        android:id="@+id/imageSwitcher1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
    </ImageSwitcher>

</LinearLayout>

3. 新增HelloImageSwitcher.java 程式

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher.ViewFactory;


public class HelloImageSwitch extends Activity {
// 當前顯示的圖片索引
private int index;
// 圖片陣列
private int[] images = { R.drawable.sakura01s, R.drawable.sakura02s,
R.drawable.sakura03s, R.drawable.sakura04s, R.drawable.sakura05s,
R.drawable.sakura06s };

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 設定全銀幕
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.helloimageswitcher);
// 得到ImageSwitcher 物件
final ImageSwitcher is = (ImageSwitcher) findViewById(R.id.imageSwitcher1);
// 實現並設置工廠內部介面的makeView 方法,用來顯示視圖。
is.setFactory(new ViewFactory() {
@Override
public View makeView() {
return new ImageView(HelloImageSwitch.this);
}
});
// 設置圖片來源
is.setImageResource(images[index]);
// 設置點擊監聽器
is.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 點擊切換圖片
index++;
if (index >= images.length) {
index = 0;
}
is.setImageResource(images[index]);
}
});
// 設定切入動畫
is.setInAnimation(AnimationUtils.loadAnimation(getApplicationContext(),
android.R.anim.slide_in_left));
// 設定切出動畫
is.setOutAnimation(AnimationUtils.loadAnimation(
getApplicationContext(), android.R.anim.slide_out_right));
} }

沒有留言: