现在的位置: 首页 > 综合 > 正文

Android学习笔记之ImageSwitcher(2)(上一张,下一张按钮)

2013年07月14日 ⁄ 综合 ⁄ 共 2257字 ⁄ 字号 评论关闭

package xiaosi.imageswitcher;

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

public class ImageSwitcherActivity extends Activity implements ViewFactory {
	
	private ImageSwitcher is_imageSwitcher;

	//存放图片id的int数组
	private int[] images={
		 R.drawable.a,
		 R.drawable.b,
		 R.drawable.c,
		 R.drawable.d,
		 R.drawable.e,
		 R.drawable.f,
		 R.drawable.g,
		 R.drawable.h,};

	//下一张和上一张按钮
	private ImageButton next;
	private ImageButton last;
	private int index=0;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        is_imageSwitcher=(ImageSwitcher)findViewById(R.id.is_imageswitch);
        last=(ImageButton)findViewById(R.id.last);
        next=(ImageButton)findViewById(R.id.next);
        
        //imageSwticher必须设置一个viewfactory后才可以查看图片
        is_imageSwitcher.setFactory(this);

        //设置图片资源id
        is_imageSwitcher.setBackgroundResource(images[index]);
     }
    
     public View makeView() {
    	   //定义每个图像的显示大小
    	   ImageView imageView = new ImageView(this);
    	   imageView.setLayoutParams(new ImageSwitcher.LayoutParams(300, 300));
    	   
    	   return imageView;
 	}
    

    //上一张的按钮事件
    public void onClickLast(View v)
    {
    	if(index == 0){
    		index = images.length-1;
    	}
    	else{
    		index--;
    	}
		is_imageSwitcher.setBackgroundResource(images[index%images.length]);
    }
    

    //下一张的按钮事件
    public void onClickNext(View v)
    {
    	index++;
		is_imageSwitcher.setBackgroundResource(images[index%images.length]);
    }
}

 

mian.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
 	android:layout_height="fill_parent">
    
 	<ImageSwitcher android:id="@+id/is_imageswitch"
  	    android:layout_width="fill_parent" 
  	    android:layout_height="fill_parent">
  	</ImageSwitcher>
    
 	
 	<LinearLayout
    android:orientation="horizontal" 
    android:layout_width="fill_parent"
 	android:layout_height="wrap_content">
    <ImageButton
        android:src="@drawable/previous" 
  	    android:id="@+id/last" 
  	    android:layout_width="40dp"
   		android:layout_height="40dp" 
   		android:layout_marginRight="10dp"
   		android:onClick="onClickLast"/>
 	 <ImageButton 
 	     android:src="@drawable/next" 
 	     android:id="@+id/next" 
 	     android:layout_width="40dp"
   		 android:layout_height="40dp"
   		  android:onClick="onClickNext"
   		 />
    </LinearLayout>
</FrameLayout>

 

 

源代码下载:点击下载

 

 

【上篇】
【下篇】

抱歉!评论已关闭.