万书网 > 文学作品 > Android从入门到精通 > 第46页

第46页





super.onPostExecute(result);



}



}

(5)在onCreate()方法的最后执行自定义的任务MyTack,具体代码如下:

new  MyTack().execute();  //执行自定义任务

运行本实例,首先显示如图4.11所示的页面内容,当图像载入完毕后,再显示如图4.12所示的完成页面。



图4.11 在标题上显示载入进度条



图4.12 页面载入完毕的效果

4.1.9 范例2:幻灯片式图片浏览器

例4.10   在Eclipse中创建Android项目,名称为4.10,实现幻灯片式图片浏览器。(实例位置:光盘\TM\sl\4\4.10)

(1)修改新建项目的res\layout目录下的布局文件main.xml,将默认添加的TextView组件删除,并且将默认的线性布局管理器设置为水平居中显示,然后添加一个图像切换器ImageSwitcher组件,并设置其顶部边距,最后添加一个画廊视图Gallery组件,并设置其各选项的间距和未选中项的透明度。修改后的代码如下:




android:orientation="vertical"



android:layout_width="fill_parent"



android:layout_height="fill_parent"



android:gravity="center_horizontal"



android:id="@+id/llayout"



>






android:id="@+id/imageSwitcher1"



android:layout_weight="2"



android:paddingTop="30px"



android:layout_width="wrap_content"



android:layout_height="wrap_content"  >










android:id="@+id/gallery1"



android:spacing="5px"



android:layout_weight="1"



android:unselectedAlpha="0.6"



android:layout_width="match_parent"



android:layout_height="wrap_content"  />





(2)在主活动MainActivity中,定义一个用于保存要显示图片id的数组(需要将要显示的图片复制到res\drawable文件夹中)和一个用于显示原始尺寸的图像切换器,关键代码如下:

private  int[]  imageId  =  new  int[]  {  R.drawable.img01,  R.drawable.img02,



R.drawable.img03,  R.drawable.img04,  R.drawable.img05,



R.drawable.img06,  R.drawable.img07,  R.drawable.img08,



R.drawable.img09,  R.drawable.img10,  R.drawable.img11,



R.drawable.img12,  };  //定义并初始化保存图片id的数组



private  ImageSwitcher  imageSwitcher;  //声明一个图像切换器对象

(3)在主活动的onCreate()方法中,获取在布局文件中添加的画廊视图和图像切换器,关键代码如下:

Gallery  gallery  =  (Gallery)  findViewById(R.id.gallery1);  //获取Gallery组件



imageSwitcher  =  (ImageSwitcher)  findViewById(R.id.imageSwitcher1);  //获取图像切换器

(4)为图像切换器设置淡入淡出的动画效果,然后为其设置一个ImageSwitcher.ViewFactory对象,并重写makeView()方法,最后为图像切换器设置默认显示的图像,关键代码如下:

//设置动画效果



imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,



android.R.anim.fade_in));  //设置淡入动画



imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,



android.R.anim.fade_out));  //设置淡出动画



imageSwitcher.setFactory(new  ViewFactory()  {



@Override



public  View  makeView()  {



ImageView  imageView  =  new  ImageView(MainActivity.this);  //实例化一个ImageView类的对象



imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);  //设置保持纵横比居中缩放图像



imageView.setLayoutParams(new  ImageSwitcher.LayoutParams(



LayoutParams.WRAP_CONTENT,  LayoutParams.WRAP_CONTENT));



return  imageView;  //返回imageView对象



}



});

(5)创建BaseAdapter类的对象,并重写其中的getView()、getItemId()、getItem()和getCount()方法,其中最主要的是重写getView()方法来设置显示图片的格式,具体代码如下:

BaseAdapter  adapter  =  new  BaseAdapter()  {



@Override



public  View  getView(int  position,  View  convertView,  ViewGroup  parent)  {



ImageView  imageview;  //声明ImageView的对象



if  (convertView  ==  null)  {



imageview  =  new  ImageView(MainActivity.this);  //实例化ImageView的对象



imageview.setScaleType(ImageView.ScaleType.FIT_XY);  //设置缩放方式



imageview