編輯:關於Android編程
package com.example.utils; import java.io.ByteArrayOutputStream; import java.io.InputStream; public class StreamTool { public static byte[] readInputStream(InputStream inStream) throws Exception { ByteArrayOutputStream outStream = new ByteArrayOutputStream();// 輸出流,寫到內存 byte[] buffer = new byte[1024];// 1K緩沖區容量 int len = 0; while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len);// 從數組buffer中讀取從0到len的數據 } inStream.close(); return outStream.toByteArray(); } }
package com.example.image; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import com.example.utils.StreamTool; public class ImageService { public static byte[] getImage(String path) throws Throwable { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5 * 1000); InputStream inStream = conn.getInputStream();// 通過輸入流獲取圖片數據 return StreamTool.readInputStream(inStream);// 得到的圖片的二進制數據 } }
package com.example.image; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; public class ImageActivity extends Activity { private static final String TAG = "ImageActivity"; private EditText pathText; private ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_image); pathText = (EditText) this.findViewById(R.id.urlpath); imageView = (ImageView) this.findViewById(R.id.show); Button button = (Button) this.findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String path = pathText.getText().toString(); try { byte[] data = ImageService.getImage(path); Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); imageView.setImageBitmap(bitmap);// 顯示圖片 } catch (Throwable e) { Toast.makeText(ImageActivity.this, R.string.error, Toast.LENGTH_LONG) .show(); Log.e(TAG, e.toString()); } } }); } } // //
說明: 視圖列表(ListView和ListActivity)與AutoComplete、Spinner類似,它們都需要一個供顯示的列表項,可以需
先上幾張效果圖:在加載多圖片時,我們采用後進先出策略(即滑動到哪裡就先加載哪裡的圖片),節省了內存的使用,也有了更好的用戶體驗。接著我們就先定義自己的ImageLoade
之前實現過html5版的鐘表,html5也有一個畫板屬性Canvas,相對於安卓的Canvas來說html5的功能要強大的多,就拿鐘表的實現,html5要方便
花了幾天時間,研究了一下Java的反射機制。在這裡總結一下這幾天學習的成果,一來分享自己的學習過程和在學習中遇到的問題,二來是給像我一樣不太了解Java反射機制的同學做一