有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java根据父级Android Studio的维度设置宽度和高度

我在一个线性布局中动态添加ImageView,它位于水平滚动视图中

现在,我想基于此水平滚动视图的父线性布局设置这些图像视图的宽度和高度

这是我的xml(信息\u imagescrollview\u item.xml):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
    安卓:id="@+id/parentlayout"
    安卓:layout_width="match_parent"
    安卓:layout_height="match_parent"
    安卓:paddingTop="5dp"
    安卓:paddingBottom="5dp">
    <HorizontalScrollView
        安卓:id="@+id/horizontal_scroll"
        安卓:layout_width="match_parent"
        安卓:layout_height="wrap_content" >
        <LinearLayout
            安卓:id="@+id/linear"
            安卓:layout_width="wrap_content"
            安卓:layout_height="match_parent"
            安卓:orientation="horizontal" >
        </LinearLayout>
    </HorizontalScrollView>
</LinearLayout>

这是我的代码:

View contentView = inflater.inflate(R.layout.information_imagescrollview_item, container, false);
LinearLayout scrollViewLayout = (LinearLayout) contentView.findViewById(R.id.linear);
for(Object intObj : page.content) {
    ImageView imageView = new ImageView(this.getContext());
    Drawable myDrawable = getResources().getDrawable((int) intObj);
    imageView.setImageDrawable(myDrawable);
    scrollViewLayout.addView(imageView);
}
page.addView(contentView);

如何将每个imageView设置为与xml中的parentlayout具有相同的宽度和高度


共 (1) 个答案

  1. # 1 楼答案

    可以通过代码更改动态视图的尺寸。所以我敢打赌,在将for循环添加到线性布局之前,您应该更改ImageView循环中的布局参数,如下所示:

    for(Object intObj : page.content) {
        ImageView imageView = new ImageView(this.getContext());
        Drawable myDrawable = getResources().getDrawable((int) intObj);
        imageView.setImageDrawable(myDrawable);
        //Changing height...
        imageView.getLayoutParams().height = ViewGroup.LayoutParams.MATCH_PARENT;
        //...and width
        imageView.getLayoutParams().width = ViewGroup.LayoutParams.MATCH_PARENT;
        scrollViewLayout.addView(imageView);
    }
    

    这将把ImageView的宽度和高度设置为包含LinearLayout的宽度和高度