textview实现图片切换效果

来源:互联网 发布:淘宝网百雀羚旗舰店 编辑:程序博客网 时间:2024/05/16 12:43

1、在activity_main中创建一个imageview和一个LinearLayout布局,其中Linearlayout中含有两个button和一个view

<ImageView 
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:id="@+id/image"
    android:src="@drawable/a"
    />
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >
    <Button 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/pre"
        android:text="@string/pre"/>
    <View 
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_weight="1"/>
    <Button 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/next"        
        android:text="@string/next"/>
    
</LinearLayout>

2、初始化imageview和两个button按钮

private Button pre, next;
private ImageView image;

image=(ImageView) findViewById(R.id.image);
pre = (Button) findViewById(R.id.pre);
next = (Button) findViewById(R.id.next);

3、对两个按钮添加监听事件

pre.setOnClickListener(this);
next.setOnClickListener(this);

4、这里采用implements的方式

implements OnClickListener

5、创建系统自带方法

public void onClick(View v) {
// TODO Auto-generated method stub


switch (v.getId()) {
case R.id.pre:


position--;
if (position < 0) {
position = images.length-1;
}
image.setImageResource(images[position]);
break;
case R.id.next:
position++;
if (position >= images.length) {
position = 0;
}
image.setImageResource(images[position]);
break;
default:
break;
}
}

6、定义一个position代表当前所在图片的位置,定义一个images数组来接收这些图片

private int position=0;
private int[] images = { R.drawable.a, R.drawable.b, R.drawable.c, R.drawable.d, R.drawable.e };


原创粉丝点击