根据父级父级Android Studio的尺寸设置宽度和高度

时间:2017-03-09 10:04:00

标签: java android-studio imageview horizontalscrollview

我在LinearLayout中动态添加ImageViews,它位于Horizo​​ntalScrollView内。

现在我想根据此Horizo​​ntalScrollView的父LinearLayout设置这些ImageView的宽度和高度。

这是我的xml(information_imagescrollview_item.xml):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/parentlayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="5dp"
    android:paddingBottom="5dp">
    <HorizontalScrollView
        android:id="@+id/horizontal_scroll"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
        <LinearLayout
            android:id="@+id/linear"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android: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 个答案:

答案 0 :(得分:1)

可以通过代码更改动态视图的尺寸。所以我敢打赌你应该在ImageView循环中更改for的布局参数,然后再将它添加到LinearLayout中,如下所示:

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的宽度和高度。