【问题标题】:ImageButton displays differently when created dynamicallyImageButton 在动态创建时显示不同
【发布时间】:2017-02-14 23:42:35
【问题描述】:

我有一个基于GridLayout 的视图,我正在向其中动态添加几个ImageButtons。我试图理解为什么当我从布局 xml 文件中对 ImageButtons 进行膨胀时,它们的样式正确,但当我直接使用 ImageButton 构造函数创建它们时却没有。

GridLayout 和 ImageButtons 之前都在同一个布局 .xml 文件中定义(并按预期呈现):

<ScrollView 
    style="@style/my_list_style"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="12dp">

        <GridLayout
            android:id="@+id/my_list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center">

            <!-- These ImageButtons are being converted to dynamic. --> 
            <ImageButton
                style="@style/my_button_style"
                android:src="@drawable/image1" />

            <ImageButton
                style="@style/my_button_style"
                android:src="@drawable/image2" />

        </GridLayout>
    </LinearLayout>
</ScrollView>

为了将 ImageButtons 转换为动态,我首先将它们从布局文件中删除,并使用如下代码在运行时添加它们:

ImageButton imageButton = new ImageButton(context, null, R.style.my_button_style);
imageButton.setImageResource(R.drawable.image1);
parent.addView(imageButton);

但按钮未能正确呈现;它们没有居中,并且它们的大小看起来不正确/不均匀。

然后我尝试创建一个新的布局文件,只包含 ImageButton 及其样式:

<ImageButton
    style="@style/my_button_style"/>

当我在运行时将此布局膨胀到 GridView 中时,一切看起来都符合预期:

LayoutInflater inflater = LayoutInflater.from(context);
ImageButton imageButton = (ImageButton) inflater.inflate(
    R.layout.my_button_layout, parent, false);
imageButton.setImageResource(R.drawable.image1);
parent.addView(imageButton);

为什么使用 LayoutInflator 膨胀视图会产生与直接从其构造函数创建按钮不同的结果?

【问题讨论】:

    标签: android android-layout


    【解决方案1】:

    因为手动创建ImageButton时,没有指定其父级,因此它不知道其父级的布局参数,无法按预期布局。

    另一方面,当您通过LayoutInflater 对其进行膨胀时,您指定的是parent。然后将正确的布局参数传递给孩子。这就是你看到差异的原因。

    看看 Dave Smith 的 detailed article

    【讨论】:

    • 当我调用addView 时,框架无法推断父级的LayoutParams 对我来说并不明显。显然,这必须在 View 实例化时发生。感谢您的链接。
    猜你喜欢
    • 2017-08-18
    • 1970-01-01
    • 2016-08-07
    • 1970-01-01
    • 2015-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多