例子1:android加載自己文件夾的圖片,使用R類
main.xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ImageView
android:id="@+id/iv1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/longshuai" <!-- longshuai.png為圖片的名稱,記在資源文件里頭,不用文件名后綴-->
/>
</LinearLayout>
注意:強調一下,資源文件的圖片命名規則比較嚴格,由[a-z]和數字和“_”組成,而且不能數字開頭,我就常犯傻,命名老是數字或者大寫字母開頭,這種錯誤——囧。。
我們要把longshuai.png導入到res中,最簡單的方式就是直接找到這個文件夾,復制進去
之后右鍵更新,我們就可以在res中看到自己的圖片了
不用寫代碼。。直接用自動生成的代碼。。
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
效果如下:
2、加載本地圖片(其實主要是SdCard中圖片)
關于SdCard的使用,可以參見 http://longshuai2007.blog.163.com/blog/static/1420944142011611103950500/
xml文件同上面的是一樣的,并不需要修改
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView image1 = (ImageView) findViewById(R.id.iv1); //獲得ImageView對象
/*為什么圖片一定要轉化為 Bitmap格式的!! */
Bitmap bitmap = getLoacalBitmap("/sdcard/tubiao.jpg"); //從本地取圖片(在cdcard中獲取) //
image1 .setImageBitmap(bitmap); //設置Bitmap
}
/**
* 加載本地圖片
* @param url
* @return
*/
public static Bitmap getLoacalBitmap(String url) {
try {
FileInputStream fis = new FileInputStream(url);
return BitmapFactory.decodeStream(fis); ///把流轉化為Bitmap圖片
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
}
顯示效果如下:
3、獲取網絡上的圖片
mian.xml文件和1中一樣,并不需要修改!
代碼:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView image1 = (ImageView) findViewById(R.id.iv1);
Comments
-
# re: android使用ImageView加載本地SdCard圖片和加載網絡圖片
Posted @ 2016-04-11 15:59
你導包正確嗎,我試過那段代碼了沒問題啊,可以加載網絡圖片 回復 更多評論
-
# re: android使用ImageView加載本地SdCard圖片和加載網絡圖片
Posted @ 2016-04-11 16:02
HttpURLConnection這個類你是導這個包嗎java.net.HttpURLConnection
回復 更多評論