版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_27384607/article/details/47088157
ImageView是关于图像视图的组件,继承自View,主要功能是显示darwable对象(图像,xml文件等)。
重要属性:
android:src设置ImageView所显示的Drawable对象id。
android:adjustViewBounds设置ImageView是否调整自己的边界来保持所显示图片的长宽比。
android:maxHeight最大高度
android:maxWidth最大宽度
android;scaleType 设置所显示图片如何缩放或移动以适应ImageView的大小
android:scaleType
Constant | Value | Description |
---|---|---|
matrix |
0 | |
fitXY |
1 | |
fitStart |
2 | |
fitCenter |
3 | |
fitEnd |
4 | |
center |
5 | |
centerCrop |
6 | |
centerInside |
7 |
测试实例,一个浏览图片的小应用。
应用实现一个简单的浏览图片的功能,用户可以通过点击previous按钮浏览上一张图片,点击next按钮浏览小一张图片。
最终效果:
进入应用显示的默认图片:
布局文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#E3E3E3">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="horizontal" >
<Button
android:id="@+id/previous"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="上一张" />
<Button
android:id="@+id/next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="下一张" />
</LinearLayout>
<ImageView
android:id="@+id/img"
android:layout_width="fill_parent"
android:layout_height="400px"
android:background="#ffffff"
android:src="@drawable/jay1"
android:scaleType="fitCenter"
android:layout_marginTop="30dip"
/>
</LinearLayout>
java文件
package com.example.login;
import android.app.Activity;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity {
int[] images = new int[]{
R.drawable.jay1,
R.drawable.jay2,
R.drawable.jay3,
R.drawable.jay4,
};
int ImageNum = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.imageview);
final Button previous = (Button)findViewById(R.id.previous);
final Button next = (Button)findViewById(R.id.next);
final ImageView image = (ImageView)findViewById(R.id.img);
OnClickListener listener = new OnClickListener(){
@Override
public void onClick(View v){
//如果没有回收图片,则回收,防止OutOfMemery错误
BitmapDrawable bitmapDrawable = (BitmapDrawable)image.getDrawable();
if(!bitmapDrawable.getBitmap().isRecycled())
bitmapDrawable.getBitmap().recycle();
if(v == previous)
{
if(ImageNum < 0) ImageNum = 3;
image.setImageBitmap(BitmapFactory.decodeResource(getResources(),
images[ImageNum--]));
}
if(v == next)
{
if(ImageNum > 3) ImageNum = 0;
image.setImageBitmap(BitmapFactory.decodeResource(getResources(),
images[ImageNum++]));
}
}
};
previous.setOnClickListener(listener);
next.setOnClickListener(listener);
}
}
努力的程序员一定会找到漂亮的妹子