請幫我用這些代碼,它不顯示來自URL的圖像。Android - 從URL加載圖像不起作用
另一個問題,如何調試每個功能,如「url.openConnection」,「getInputStream」....以確認它們是否正常工作?
謝謝
public class MainActivity extends Activity {
Bitmap bitmap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout mainLayout = (LinearLayout)findViewById(R.id.mainlayout);
// ImageView
ImageView imgView = new ImageView(this);
mainLayout.addView(imgView);
bitmap = loadImage("https://www.google.com.vn/logos/doodles/2014/dian-fosseys-82nd-birthday-5702250374627328-hp.jpg");
imgView.setImageBitmap(bitmap);
}
public Bitmap loadImage(String src)
{
try
{
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
input.close();
return myBitmap;
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
}
}
請加mainlayout的代碼請 – Arshak92
還需要設置佈局參數ImageView的 –
主要佈局是LinearLayout中,沒有任何部件。我在代碼中創建它們 –