【发布时间】: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 膨胀视图会产生与直接从其构造函数创建按钮不同的结果?
【问题讨论】: