【问题标题】:xml layout visibly different to code generated layoutxml 布局与代码生成的布局明显不同
【发布时间】:2020-08-02 15:05:41
【问题描述】:

项目将显示在GridView

<GridView
    android:id="@+id/month_list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="@dimen/activity_half_horizontal_margin"
    android:paddingRight="@dimen/activity_half_horizontal_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:stretchMode="columnWidth"
    android:horizontalSpacing="4dp"
    android:verticalSpacing="4dp"/>

用于在代码中生成的项目的布局:

private LinearLayout getMonthImageView() {
    LinearLayout layout = new LinearLayout(context);
    layout.setOrientation(LinearLayout.VERTICAL);

    TextView text = new TextView(context);
    text.setGravity(Gravity.CENTER);
    text.setSingleLine();
    layout.addView(text, 0);

    ImageView image = new ImageView(context);
    image.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
    image.setAdjustViewBounds(true);
    layout.addView(image, 1);

    return layout;
}

我已经将该部分重构为来自 xml 布局文件:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/month_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:singleLine="true"/>

    <ImageView
        android:id="@+id/month_icon"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerInside"
        android:adjustViewBounds="true"/>

</LinearLayout>

这产生了不想要的可见效果:GridView 中的项目之间的差距变大了,就好像这些项目获得了一些填充或边距(显然不是这种情况)。这是为什么?在代码中生成的项目与来自 xml 布局文件的项目有什么区别?如何让物品再次放大?

之前(代码布局):

之后(xml布局):

【问题讨论】:

    标签: android android-layout android-xml android-gridview


    【解决方案1】:

    我看到了一些潜在的问题,但如果没有图片描述您的问题,我很难准确地说出是什么。 您可能想查看以下几点:

    1. 如果你正在膨胀LinearLayout,你应该避免android:layout_height="match_parent",因为它占用了最大的空间(通常是整个屏幕),即使你可能不需要它。

    2. 我在想ImageView 可能不应该等于父级,但有不同的大小。 这样,它也占用了其父级中可能不需要的最大空间。

    我的建议是,试试RelativeLayout,加上android:layout_width="match_parent"android:layout_height="wrap_content

    然后使用不同的layout_align 选项来对齐顶部的所有内容,并为您的ImageView 提供一些特定尺寸。

    这只是我的猜测,不过我可能错了。

    【讨论】:

    • 嗯.. 这并不能真正解决我遇到的问题。我不想更改 Layout 类。我想知道的是:为什么布局是来自代码还是来自xml?
    • 我已经添加了一些图片。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-02
    • 2023-03-25
    • 2014-12-13
    • 2015-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多