ImageSwitch切换图片
1. ImagSwitcherActivity:
1 import android.app.Activity;
2 import android.os.Bundle;
3 import android.view.View;
4 import android.view.View.OnClickListener;
5 import android.widget.Button;
6 import android.widget.ImageSwitcher;
7 import android.widget.ImageView;
8 import android.widget.LinearLayout;
9 import android.widget.ViewSwitcher.ViewFactory;
10
11 public class ImagSwitcherActivity extends Activity implements ViewFactory, OnClickListener
12 {
13 // 创建一个ImageSwitch对象
14 private ImageSwitcher imageSwitcher;
15
16 // ImageSwitch的ID
17 private static final int SWITCHER_ID = 0x123456;
18
19 // “上一张”按钮的ID
20 private static final int BUTTON_UP = 0x123457;
21
22 // “下一张”按钮的ID
23 private static final int BUTTON_DOWN = 0x123458;
24
25 // 索引
26 private int index = 0;
27
28 private static final int[] imagelist = {R.drawable.imag1, R.drawable.imag2, R.drawable.imag3, R.drawable.imag4,
29 R.drawable.imag5, R.drawable.imag6, R.drawable.imag7, R.drawable.imag8, R.drawable.imag9, R.drawable.imag9,
30 R.drawable.imag10, R.drawable.imag11, R.drawable.imag12};
31
32 @Override
33 public void onCreate(Bundle savedInstanceState)
34 {
35 super.onCreate(savedInstanceState);
36 // 创建一个线性布局LinearLayout
37 LinearLayout linearLayout = new LinearLayout(this);
38 //创建ImageSwitch对象
39 imageSwitcher = new ImageSwitcher(this);
40 //在线性布局中添加ImageSwitch
41 linearLayout.addView(imageSwitcher);
42 //设置imageSwitch的ID
43 imageSwitcher.setId(SWITCHER_ID);
44 //设置imagSwitch对象的数据源
45 imageSwitcher.setFactory(this);
46 imageSwitcher.setImageResource(imagelist[index]);
47 //设置显示上面创建的线性布局
48 setContentView(linearLayout);
49
50 // 创建“下一张”按钮
51 Button nex_button = new Button(this);
52 nex_button.setId(BUTTON_DOWN);
53 nex_button.setText("下一张");
54 nex_button.setOnClickListener(this);
55 //(100, 100)->表示按鈕的大小
56 LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(100, 100);
57 linearLayout.addView(nex_button, params);
58 // 创建“上一张”按钮
59 Button up_button = new Button(this);
60 up_button.setId(BUTTON_UP);
61 up_button.setText("上一张");
62 up_button.setOnClickListener(this);
63 linearLayout.addView(up_button, params);
64 }
65
66 @Override
67 public View makeView()
68 {
69 // 将所有图片通过ImageView来显示
70 return new ImageView(this);
71 }
72
73 @Override
74 public void onClick(View arg0)
75 {
76 switch (arg0.getId())
77 {
78 // 下一页
79 case BUTTON_DOWN:
80 index++;
81 if (index > imagelist.length)
82 {
83 index = 0;
84 }
85 imageSwitcher.setImageResource(imagelist[index]);
86 break;
87 // 上一张
88 case BUTTON_UP:
89 index--;
90 if (index < 0)
91 {
92 index = 0;
93 }
94 imageSwitcher.setImageResource(imagelist[index]);
95 break;
96 }
97 }
98 }
2. 效果图: