现在我有一个LocationAdapter
类,它接收我的"Location"
对象,并将每个Location
显示为ListView
。我试图在Bitmap
图像中传递它并让它在ListView行中显示该图像。它工作正常,但即使加载了行中的文本,图像也需要一段时间才能加载。我正在测试一个实际的设备。这是我的活动代码:
public class MainActivity extends ActionBarActivity {
ArrayList<Location> arrayOfLocations;
LocationAdapter adapter;
private static Bitmap bitmap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
// Construct the data source
arrayOfLocations = new ArrayList<Location>();
// Create the adapter to convert the array to views
adapter = new LocationAdapter(this, arrayOfLocations);
Bitmap image = getBitmapFromID(1);
adapter.add(new Location(image, "Place 1",
"We have the freshest fruit in the whole world!", "2 miles",
"8-5 mon-sat\nclosed sun"));
adapter.add(new Location(image, "Place 2",
"We have the freshest fruit in the whole world!", "2 miles",
"8-5 mon-sat"));
adapter.add(new Location(image, "Place 3",
"We have the best cakes in the whole world!", "2 miles",
"8-5 mon-fri\n10-1 sat\nclosed sun\nclosed Memorial Day"));
adapter.add(new Location(image, "Fruit Stand",
"Best place!", "2 miles",
"8-5 mon-sat"));
adapter.add(new Location(image, "Place 4",
"Food!", "2 miles",
"8-5 mon-sat"));
adapter.add(new Location(image, "Place 5",
"Toys!", "2 miles",
"8-5 mon-sat"));
// Attach the adapter to a ListView
ListView listView = (ListView) findViewById(R.id.listView1);
View header = (View) getLayoutInflater().inflate(
R.layout.listview_header, null);
listView.addHeaderView(header);
listView.setAdapter(adapter);
}
public static Bitmap getBitmapFromID(int id) {
//final Bitmap bitmap;
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
bitmap = BitmapFactory
.decodeStream((InputStream) new URL(
"http://icons.iconarchive.com/icons/yellowicon/game-stars/256/Mario-icon.png")
.getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
return bitmap;
}
}
我做错了什么吗?这需要一段时间加载是正常的吗?谢谢!
答案 0 :(得分:1)
你需要在后台线程中AsyncTask你的工作。然而,为了更好的方法,请看一下:
https://stackoverflow.com/a/23941258/276949
Android Volley是Google推出的一款非常新的非详细资料库,可以很好地加载图像,并且可以自动处理单独线程上的所有下载。
答案 1 :(得分:0)
加载位图可能需要一段时间,您可以在此处阅读:Android doc。但是,您需要同步您的线程,因为在调用start()之后,该方法立即返回。你需要收到一个&#34;嘿,我已经完成了#34;从你的线程,然后加载位图。
答案 2 :(得分:0)
您是否可以将Mario_icon.png放置在应用内部,而不是通过网址进行访问?这样,应用程序将花费更少的时间来检索图像,并且它将允许应用程序需要更少的权限
当您需要连接到网址时,加载图片需要更长的时间。