每次点击手提箱中的按钮,我都会尝试获取图像,但它不起作用。 我也没有错误,所以我真的不知道问题所在。我想我已经拥有了最重要的东西。
爪哇
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
// private GoogleApiClient client;
private ImageView iv;
private int a;
private Bitmap bitmap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// iv = (ImageView) findViewById(R.id.imageView1);
// bitmap = getBitmapFromURL("http://icons.iconarchive.com/icons /crountch/one-piece-jolly-roger/72/Luffys-flag-2-icon.png");
// iv.setImageBitmap(bitmap);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
// client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
public void buttonOnClick(View v) {
// do something when the button is clicked
Button button = (Button) v;
a = (byte) (Math.random() * 2);
switch (a) {
case 1:
iv = (ImageView) findViewById(R.id.imageView1);
bitmap = getBitmapFromURL("http://icons.iconarchive.com/icons/crountch/one-piece-jolly-roger/72/Luffys-flag-2-icon.png");
iv.setImageBitmap(bitmap);
break;
// iv.setImageBitmap(bitmap);
case 2:
break;
}
}
public Bitmap getBitmapFromURL(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);
return myBitmap;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return null;
}
}
}
XML
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Image text"
android:id="@+id/textView"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true"
android:layout_marginTop="82dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Image"
android:id="@+id/button"
android:onClick="buttonOnClick"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:layout_marginTop="41dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView1"
android:layout_alignParentBottom="true"
android:layout_alignRight="@+id/textView"
android:layout_alignEnd="@+id/textView"
android:layout_marginBottom="106dp" />
</RelativeLayout>
答案 0 :(得分:-1)
你正试图在主线程上建立网络。
如果你读了你的logcat,你得到'android.os.NetworkOnMainThreadException'
Picasso非常适合下载图像并将其放置在您的视图中。