【问题标题】:Inflation of View Failing视图膨胀失败
【发布时间】:2016-03-07 08:20:17
【问题描述】:

我一直在尝试使用循环以编程方式膨胀按钮的线性布局,但它根本没有显示在 UI 中。但是,数组会被填充。

我的按钮 xml:

<Button xmlns:android="http://schemas.android.com/apk/res/android"
    style="@style/BlackKey">
</Button>

我的风格资源:

<style name="BlackKey">
    <item name="android:layout_height">0dp</item>
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_weight">2</item>
    <item name="android:background">@color/black</item>
    <item name="android:layout_margin">3dp</item>
</style>

我的初始化代码:

container = (FrameLayout) findViewById(R.id.mainframe);
public Button [] BLACKKEYS = new Button[5];

LinearLayout blackkeys = new LinearLayout(this);
blackkeys.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
blackkeys.setOrientation(LinearLayout.HORIZONTAL);

for (int i = 0; i < 8; i++){
    Button newbutton = (Button) LayoutInflater.from(this).inflate(R.layout.blackkey, blackkeys, false);
    blackkeys.addView(newbutton);
    BLACKKEYS[i] = newbutton;
}

container.addView(blackkeys);

【问题讨论】:

    标签: android view android-inflate


    【解决方案1】:

    所以我继续尝试使用 Android Studio 提供的代码,我也收到了一个空白屏幕。我看到的主要问题是在您的 BlackKey 样式中,提供了 layout_weight,layout_height 设置为 0dp,layout_widthMATCH_PARENT em>,但方向是水平的 -- 如果按钮出现,这将使它只显示一个按钮。

    如果我如何理解您希望它如何显示(五个按钮在水平方向上并排,宽度相等),如下所示:

    然后你可以像这样修改 BlackKey 样式:

    <style name="BlackKey">
            <item name="android:layout_height">wrap_content</item>
            <item name="android:layout_width">wrap_content</item>
            <item name="android:layout_weight">2</item>
            <item name="android:background">@color/black</item>
            <item name="android:layout_margin">3dp</item>
        </style>
    

    还有一个提示,如果您使用的是 Android Studio,您可以先检查按钮是否显示在 设计选项卡 中,看看它是否显示正确显示在屏幕上。如果它没有显示在那里,然后尝试修改它。希望这对您有所帮助。如果您还有其他问题,或者如果这与您正在寻找的答案相似但不完整,请发表评论,我会尽力帮助您。 :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-29
      • 2017-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多