级联使用 LayoutInflater 忽略了 Android LayoutWidth

标签 android

我正在构建一个按钮金字塔,并希望金字塔的大小能够动态变化。为实现这一点,我有非常基本的 XML 文件来表示 Activity 、 Activity 的每一行和每个按钮。我正在根据对 this question 的已接受响应对解决方案进行建模.金字塔构造正确,但未遵守 50dip 按钮宽度。任何想法为什么?有更好的方法吗?

主.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/pyramid" 
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center_horizontal"
/>

行.xml:

<?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/row"  
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center_horizontal"/>

btn.xml:

<?xml version="1.0" encoding="utf-8"?>
    <Button xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/button" 
        android:layout_width="50dip" 
        android:layout_height="wrap_content"/>

主要 Activity :

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    inflate();
    }
private void inflate() {
    LinearLayout pyramidLayout = (LinearLayout) findViewById(R.id.pyramid);

    for (int row = 1 ; row <= mSize; ++row) {
        View rowView = getLayoutInflater().inflate(R.layout.row, null);
        LinearLayout rowLayout = (LinearLayout) rowView.findViewById(R.id.row);
        for (int column = 1; column <= row; ++column) {
            View btnView = getLayoutInflater().inflate(R.layout.btn, null);
            Button btn = (Button) btnView.findViewById(R.id.button);
            btn.setId(row*10 + column);
            rowLayout.addView(btnView);
        }
        pyramidLayout.addView(rowView); 
    }
}

最佳答案

在 btn.xml 中,将 layout_width="50dip" 更改为 width="50dip"

关于级联使用 LayoutInflater 忽略了 Android LayoutWidth,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2259647/

相关文章:

Android volley - 避免对服务器发出多个相同类型的请求?

android - 创建无拉伸(stretch)的全屏相机表面 View

android - 翻译同一 View 组内的 View

java - 对于持久性 bottomsheet,如何实现从展开状态到半展开状态的手势(向下滑动)?

java - ListView XML id 问题

java - Android 与标准 java 上的不同行为

java - Android - 如何开始新 Activity

android - ADT 在 SHIFT+F2 上使用离线文档

Android 应用程序在某些设备中显示默认的 android 图标

Android BLE 读取 Gatt 特性