使用 ScrollView 滚动图像

Scrolling images with ScrollView

使用以下 XML 和 java 代码,我将用相机拍摄的图像添加到 ScrollView 中的 LinearLayout。

XML:

    <HorizontalScrollView
        android:layout_gravity="center_vertical"
        android:scrollbars="none"
        android:layout_width="wrap_content"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/detailsback"
            android:layout_gravity="center_vertical"
            android:id="@+id/imageSlider"
            android:orientation="horizontal" >

        </LinearLayout>

    </HorizontalScrollView>

Java(在片段中运行):

private void setTakePicButton(){
    mTakePicButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mBitmap = mTextureView.getBitmap();
                Date currentDateTime = Calendar.getInstance().getTime();
                String filename = getFileName();
                FileOutputStream fileOutputStream = null;

                try {
                    fileOutputStream = new FileOutputStream( filename);
                    mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);// bmp is your Bitmap instance

                    ImageView imageView = new ImageView(getActivity());
                    imageView.setImageBitmap(mBitmap);

                    linearLayout.addView(imageView);

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {

                }
       }
    });
}

问题是每当我将图片添加到 linearLayout (id:imageSlider) 时,它都会像图片中显示的那样添加大边距

我希望图像按如下图所示的顺序显示。

如果我没理解错的话,问题是底部的图片是居中的,而不是左边的轮廓?这可能是由线性布局的 wrap_content 宽度引起的。

我还建议您使用某种列表视图而不是 LinearLayout 并手动添加项目。 RecyclerView 将是一个很好的解决方案,并且也可以设置为水平。

解决方案 01

您可以使用 FIT_XY 缩放类型

将图像设置为边界
imgview.setScaleType(ImageView.ScaleType.FIT_XY);

您可以找到所有 ScaleTypes here

解决方案 02

如果您尝试以列表形式查看图像,您可以使用 RecyclerViewCreate a List with RecyclerView

解决方案 03

如果要并排显示图像,请将layout_weight设置为imageView

这是编程方式,(最后一个参数是权重)

LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
    LayoutParams.MATCH_PARENT,
    LayoutParams.MATCH_PARENT,
    1.0f
);
imageView.setLayoutParams(param);