WEB开发网
开发学院手机开发Android 开发 Gallery 之滑动不流畅的解决办法 阅读

Gallery 之滑动不流畅的解决办法

 2012-05-26 15:38:44 来源:WEB开发网   
核心提示:Activity中的代码:<pre name="code" class="html">public class ImageScanActivity extends Activity {private MyGallery gallery;private GalleryA

Activity中的代码:

<pre name="code" class="html">public class ImageScanActivity extends Activity {
	private MyGallery gallery;
	private GalleryAdapter adapter;
	//图片数组
	private Integer[] imagesId = new Integer[] { R.drawable.a, R.drawable.b, R.drawable.c,
			R.drawable.d, R.drawable.a, R.drawable.b, R.drawable.c, R.drawable.d, R.drawable.a,
			R.drawable.b, R.drawable.c, R.drawable.d };

	private int motionStatus=0;//记录到底是向前滑动,还是向后,-1向前,1向后
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		gallery = (MyGallery) findViewById(R.id.gallery);
		adapter = new GalleryAdapter(this,imagesId);
		gallery.setAdapter(adapter);
		gallery.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				if(position==adapter.getShowingIndex()-1){//向前
					new MyTask().execute();
					motionStatus=-1;
				}
				if(position==adapter.getShowingIndex()+1){//向后
					motionStatus=1;
					new MyTask().execute();
				}
			}
			public void onNothingSelected(AdapterView<?> parent) {

			}
		});
	}
	private class MyTask extends AsyncTask<Void, Void, Void> {
		@Override
		protected Void doInBackground(Void... params) {
			int showing = adapter.getShowingIndex();// 记录当前正在显示图片的id
			Bitmap[] bitmaps = adapter.getNearBitmaps();//获得Adapter中的缓存图片数组
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inSampleSize = 2;
			if(motionStatus==-1){//向前滑动,bitmaps[0]加载新的图片
				bitmaps[2]=bitmaps[1];
				bitmaps[1]=bitmaps[0];
				if(showing>=2)
				bitmaps[0]=BitmapFactory.decodeResource(getResources(), imagesId[showing - 2],
						options);
			}
			if(motionStatus==1){//向后滑动,bitmaps[2]加载新的图片
				bitmaps[0]=bitmaps[1];
				bitmaps[1]=bitmaps[2];
				if(showing<=imagesId.length-3)
				bitmaps[2]=BitmapFactory.decodeResource(getResources(), imagesId[showing + 2],
						options);
			}
			adapter.setShowingIndex(showing+motionStatus);
			return null;
		}
	}
}

上一页  1 2 

Tags:Gallery 滑动 流畅

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接