[Android学习笔记3]ImageSwitcher

今天实现一个比较简单的图片切换效果的小程序。

利用ImageSwitcher类,通过设置一个ViewFactory工厂,实现其makeView()方法来创建显示图片的View。

方法setImageResource用来显示指定的图片资源。

 

 

1. 将8张图片放入/res/drawable目录下,同时命名为sample_0,sample_1,....sample_7等;

2. 在代码中定义资源id数组;

static final Integer[] imagelist = 
		{
			R.drawable.sample_0,
			R.drawable.sample_1,
			R.drawable.sample_2,
			R.drawable.sample_3,
			R.drawable.sample_4,
			R.drawable.sample_5,
			R.drawable.sample_6,
			R.drawable.sample_7,
		};

 

 

Activity.java

package com.luoye.allview;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher.ViewFactory;

public class SecondActivity extends Activity implements OnClickListener, ViewFactory{

	
	ImageSwitcher imageswitcher;
	private Button button_pre;
	private Button button_next;
	
	static final Integer[] imagelist = 
		{
			R.drawable.sample_0,
			R.drawable.sample_1,
			R.drawable.sample_2,
			R.drawable.sample_3,
			R.drawable.sample_4,
			R.drawable.sample_5,
			R.drawable.sample_6,
			R.drawable.sample_7,
		};
	private static int index = 0;
	
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.secondactivity);
		
		imageswitcher = (ImageSwitcher)findViewById(R.id.imageswitch);
		imageswitcher.setFactory(this);
		imageswitcher.setImageResource(imagelist[index]);
		
		button_pre = (Button)findViewById(R.id.button_pre);
		button_next = (Button)findViewById(R.id.button_next);
		
		button_pre.setOnClickListener(this);
		button_next.setOnClickListener(this);
	}

	@Override
	public View makeView() {
		// TODO Auto-generated method stub
		return new ImageView(this);
	}

	@Override
	public void onClick(View v) {                      //实现button的onClick方法
		// TODO Auto-generated method stub
		
		switch(v.getId())
		{
			case R.id.button_next:
				index++;
				if(index == imagelist.length)
				{
					index = 0;
				}
				imageswitcher.setImageResource(imagelist[index]);
				break;
			case R.id.button_pre:
				index--;
				if(index < 0)
				{
					index =  imagelist.length - 1;
				}
				imageswitcher.setImageResource(imagelist[index]);
				break;
			default:
				break;
		}
		
	}

}

布局文件:



    
    
    
    



效果:

[Android学习笔记3]ImageSwitcher_第1张图片

点击下一张后,实现了切换

[Android学习笔记3]ImageSwitcher_第2张图片

你可能感兴趣的:(Android)