view:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity" android:orientation="vertical"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/up" android:text="上一张"/> <ImageSwitcher android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:id="@+id/images"></ImageSwitcher> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/down" android:text="下一张"/> </LinearLayout>
java:
public class MainActivity extends ActionBarActivity { private int[] imageId=new int[]{R.drawable.img02,R.drawable.img03,R.drawable.img04,R.drawable.img05, R.drawable.img06,R.drawable.img07,R.drawable.img08,R.drawable.img09}; private int index=0; //当前显示的索引 private ImageSwitcher imageSwitcher;//声明一个图像切换器对象 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageSwitcher = (ImageSwitcher) findViewById(R.id.images); imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,android.R.anim.fade_in));//设置淡入动画 imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,android.R.anim.fade_out));//设置淡出效果 imageSwitcher.setFactory(new ViewSwitcher.ViewFactory() { @Override public View makeView() { ImageView imageView=new ImageView(MainActivity.this); imageView.setScaleType(ImageView.ScaleType.FIT_CENTER); //设置保持纵横比居中 imageView.setLayoutParams(new ImageSwitcher.LayoutParams( ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT )); return imageView; } }); imageSwitcher.setImageResource(imageId[index]); Button up= (Button) findViewById(R.id.up); Button down= (Button) findViewById(R.id.down); up.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (index>0){ index--; }else { index=imageId.length-1; } imageSwitcher.setImageResource(imageId[index]); //显示当前图片 } }); down.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (index>-1&&index<imageId.length-1){ index++; }else { index=0; } imageSwitcher.setImageResource(imageId[index]); //显示当前图片 } }); } }
时间: 2024-10-15 23:56:40