gpt4 book ai didi

android - 将 View 动态添加到 GridLayout 时对齐不正确

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:56:55 26 4
gpt4 key购买 nike

When added buttons by XML - All good

When adding buttons through XML

  <GridLayout
android:id="@+id/social_gl_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:alignmentMode="alignBounds"
android:columnCount="2"
android:padding="8dp">

<LinearLayout
android:layout_width="0dp"
android:layout_height="45dp"
android:layout_columnWeight="1">
<Button
android:layout_width="fill_parent"
android:layout_height="45dp"
android:background="@android:color/holo_blue_light"
android:text="Hi"/>
</LinearLayout>

<LinearLayout
android:layout_width="0dp"
android:layout_height="45dp"
android:layout_columnWeight="1">
<Button
android:layout_width="fill_parent"
android:layout_height="45dp"
android:background="@android:color/holo_green_light"
android:text="Whatsapp"/>
</LinearLayout>

<LinearLayout
android:layout_width="0dp"
android:layout_height="45dp"
android:layout_columnWeight="1">
<Button
android:layout_width="match_parent"
android:layout_height="45dp"
android:background="@android:color/holo_green_light"
android:text="This is facebook"
/>
</LinearLayout>

<LinearLayout
android:layout_width="0dp"
android:layout_height="45dp"
android:layout_columnWeight="1">
<Button
android:layout_width="match_parent"
android:layout_height="45dp"
android:background="@android:color/holo_blue_light"
android:text="On"
/>
</LinearLayout>

</GridLayout>

When added Buttons dynamically(By code)- Alignment missing, buttons not occupying complete width of a column

GridLayout gl = (GridLayout) findViewById(R.id.social_gl_content);
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
for (int i = 0 ; i < strs.length ; i++) {
View v = inflater.inflate(R.layout.grid_item, null);
Button b = (Button) v.findViewById(R.id.button);
b.setText(strs[i]);
if ( i % 2 ==0) {
b.setBackgroundColor(Color.BLACK);
}else{
b.setBackgroundColor(Color.BLUE);
}
gl.addView(v);
}

enter image description here

最佳答案

而不是传递空值:

View v = inflater.inflate(R.layout.grid_item, null);

传递 parentView 以便 v 具有正确的布局参数。

View v = inflater.inflate(R.layout.grid_item, gl, false);

关于android - 将 View 动态添加到 GridLayout 时对齐不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33821371/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com