android horizontalscrollview不能放在一个layout下面吗

2024年11月19日 11:23
有1个网友回答
网友(1):

HorizontalScrollView是一个FrameLayout ,这意味着你只能在它下面放置一个子控件,这个子控件可以包含很多数据内容。有可能这个子控件本身就是一个布局控件,可以包含非常多的其他用来展示数据的控件。这个布局控件一般使用的是一个水平布局的LinearLayout 。TextView也是一个可滚动的视图控件,所以一般不需要HorizontalScrollView
下面介绍一个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;
}