歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 【Google官方教程】第四課:在UI中顯示Bitmap

【Google官方教程】第四課:在UI中顯示Bitmap

日期:2017/3/1 10:07:17   编辑:Linux編程

譯者按: 在Google最新的文檔中,提供了一系列含金量相當高的教程。因為種種原因而鮮為人知,真是可惜!Ryan將會細心整理,將之翻譯成中文,希望對開發者有所幫助。

本系列是Google關於展示大Bitmap(位圖)的官方演示,可以有效的解決內存限制,更加有效的加載並顯示圖片,同時避免讓人頭疼的OOM(Out Of Memory)。

【Google官方教程】系列相關閱讀: http://www.linuxidc.com/search.aspx?where=nkey&keyword=14914

-------------------------------------------------------------------------------------

譯文:

這節課將我們前面幾節課學習的東西都整合起來,向你展示如何使用後台線程和Bitmap緩存加載多個Bitmap(位圖)到ViewPager和GridView組件中,並學習如何處理並發和配置變化問題。

實現加載Bitmap到ViewPager

滑動浏覽模式(Swipe View Pattern)是一種很好的浏覽詳細圖片的方式。你可以使用ViewPager組件配合PagerAdapter(適配器)來實現這種模式。然而,更加合適的適配器是FragmentStatePagerAdapter,它可以在ViewPager退出屏幕的時候自動銷毀並存儲Fragments的狀態,使得內存依然保留下來。

注意:如果你只有少量的圖片,並且確信它們不會超出程序的內存限制,使用常規的PagerAdapter或者FragmentPagerAdapter或許更加合適。

這裡有一個包含ImageView的ViewPager的實現類,Main Activity(主活動)持有這個ViewPager和Adapter。

public class ImageDetailActivity extends FragmentActivity {
public static final String EXTRA_IMAGE = "extra_image";

private ImagePagerAdapter mAdapter;
private ViewPager mPager;

// A static dataset to back the ViewPager adapter
public final static Integer[] imageResIds = new Integer[] {
R.drawable.sample_image_1, R.drawable.sample_image_2, R.drawable.sample_image_3,
R.drawable.sample_image_4, R.drawable.sample_image_5, R.drawable.sample_image_6,
R.drawable.sample_image_7, R.drawable.sample_image_8, R.drawable.sample_image_9};

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.image_detail_pager); // Contains just a ViewPager

mAdapter = new ImagePagerAdapter(getSupportFragmentManager(), imageResIds.length);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
}

public static class ImagePagerAdapter extends FragmentStatePagerAdapter {
private final int mSize;

public ImagePagerAdapter(FragmentManager fm, int size) {
super(fm);
mSize = size;
}

@Override
public int getCount() {
return mSize;
}

@Override
public Fragment getItem(int position) {
return ImageDetailFragment.newInstance(position);
}
}
}

Copyright © Linux教程網 All Rights Reserved