ImageView是基础的控件,它是android.widget.ImageView的继承类。
XML片段
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<!-- 指定资源id: @drawable/xxxxx -->
<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android: />
代码设置ImageView
在XML中ui_image3没有设置具体的src,可以在代码中通过若干中方法设置。
方式1:设置资源的ID
ImageView image = (ImageView)findViewById(R.id.ui_image3);
image.setImageResource(R.drawable.ic_launcher);
方式2:通过Bitmap
ImageView image = (ImageView)findViewById(R.id.ui_image3);
Bitmap bm = BitmapFactory.decodeResource(this.getResources(), R.drawable.png02);
//在这里可以加入对Bitmap的处理代码 ... ...
image.setImageBitmap(bm);
方式3:通过文件
对于模拟器,我们通过命令行以adb push的方式将图片文件放入文件系统的某个位置,例如sdcard中,如下图所示:
ImageView image = (ImageView)findViewById(R.id.ui_image3);
try{
String filename = Environment.getExternalStorageDirectory()+ "/wei/sunflower.jpg";
image.setImageDrawable(Drawable.createFromPath(filename));
}catch(Exception e){
Log.e("wei",e.toString());
}
方式4:通过Uri方式
ImageView image = (ImageView)findViewById(R.id.ui_image3);
image.setImageURI(Uri.parse("file://mnt/sdcard/wei/logo.jpg")); //只能是本地存储
注意URI方式只限于本地存储,不能是远端存储,如果我们设置了web URI,系统会报以下错误:
其他
如果我们希望图片来自remote,可以利用BitmapFactory.decodeStream(InputStream is),然后将Bitmap放入ImageView中。
相关链接: 我的Android开发相关文章