使用ScrollView滚动图像

时间:2018-08-23 06:37:19

标签: android scrollview android-linearlayout

使用以下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(在Fragment中运行):

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)时,它就会以较大的边距添加,例如图片中的显示

after adding the first pic

enter adding the second pic

我希望图像按照下图所示的顺序显示。 enter image description here

2 个答案:

答案 0 :(得分:1)

解决方案01

您可以使用FIT_XY比例类型将图像设置为边界

imgview.setScaleType(ImageView.ScaleType.FIT_XY);

您可以找到所有ScaleTypes here

解决方案02

如果您尝试查看类似列表的图像,则可以使用RecyclerViewCreate a List with RecyclerView

解决方案03

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

这是通过编程方式进行的操作(最后一个参数是weight)

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

答案 1 :(得分:0)

如果我的理解正确,那么问题在于底部的图像居中而不是位于左侧?这可能是由于线性布局的wrap_content宽度引起的。

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

相关问题