【问题标题】:Set width and height based on dimentions of parent's parent Android Studio根据父母的父母Android Studio的尺寸设置宽度和高度
【发布时间】:2017-03-09 10:03:59
【问题描述】:

我在 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 中的父布局具有相同的宽度和高度?

【问题讨论】:

    标签: java android-studio imageview horizontalscrollview


    【解决方案1】:

    可以通过代码更改动态视图的尺寸。所以我打赌你应该在for 循环中更改ImageView 的布局参数,然后再将其添加到您的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 的宽度和高度。

    【讨论】:

    • 如果我添加 imageView.getLayoutParams().width = ViewGroup.LayoutParams.MATCH_PARENT;图像仍然几乎是屏幕宽度的两倍。
    • 您想像在图库应用中那样一个接一个地滚动图像吗?
    • 是的。但在几个文本视图之间,
    • 我可以要求您发送草图链接或更新您的答案吗?我不想一直猜测你真正想创造什么......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-15
    • 2016-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多