由於移動設備物理顯示空間一般有限,不可能一次性的把所有要顯示的內容都顯示在屏幕上。所以各大平臺一般會提供一些可滾動的視圖來向用戶展示數據。Android平臺框架中爲我們提供了諸如ListView、GirdView、ScrollView等滾動視圖控件,這幾個視圖控件也是我們平常使用最多的。我下面介紹一下HorizontalScrollView的使用和需要注意的點
LinearLayout
。TextView也是一個可滾動的視圖控件,所以一般不需要HorizontalScrollView @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout. activity_main);
mLinearLayout = (LinearLayout) findViewById(R.id.mygallery);
File externalDir = Environment. getExternalStorageDirectory();
String photosPath = externalDir.getAbsolutePath() + "/test/";
File photosFile = new File(photosPath);
for (File photoFile : photosFile.listFiles()) {
mLinearLayout.addView(getImageView(photoFile.getAbsolutePath()));
}
}
private View getImageView(String absolutePath) {
Bitmap bitmap = decodeBitmapFromFile(absolutePath, 200, 200);
LinearLayout layout = new LinearLayout(getApplicationContext());
layout.setLayoutParams( new LayoutParams(250, 250));
layout.setGravity(Gravity. CENTER);
ImageView imageView = new ImageView(this);
imageView.setLayoutParams( new LayoutParams(200,200));
imageView.setScaleType(ImageView.ScaleType. CENTER_CROP);
imageView.setImageBitmap(bitmap);
layout.addView(imageView);
return layout;
}
private Bitmap decodeBitmapFromFile(String absolutePath, int reqWidth, int reqHeight) {
Bitmap bm = null;
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options. inJustDecodeBounds = true ;
BitmapFactory. decodeFile(absolutePath, options);
// Calculate inSampleSize
options. inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options. inJustDecodeBounds = false ;
bm = BitmapFactory. decodeFile(absolutePath, options);
return bm;
}
private int calculateInSampleSize(Options options, int reqWidth,
int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math. round((float)height / ( float)reqHeight);
} else {
inSampleSize = Math. round((float)width / ( float)reqWidth);
}
}
return inSampleSize;
}
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
// 水平直接滾動800px,如果想效果更平滑可以使用smoothScrollTo(int x, int y)
hsv.scrollTo(800, 0);
}
}, 2000);
效果大致如下