繁体   English   中英

膨胀视图失败

[英]Inflation of View Failing

我一直在尝试使用循环以编程方式扩展按钮的线性布局,但它根本没有显示在 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 Studio 提供的代码,但我也收到了一个空白屏幕。 我看到的主要问题是在你的 BlackKey 样式中,提供了layout_weightlayout_height设置为 0dp, layout_widthMATCH_PARENT ,但方向是水平的——如果按钮出现,这将使它只显示一个按钮。

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

在此处输入图片说明

然后你可以像这样修改 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,您可以先检查 Button 是否显示在Design Tab 中,以查看它是否正确显示在屏幕上。 如果它没有出现在那里,那么尝试修改它。 希望这对你有帮助。 如果您还有其他问题,或者这与您正在寻找的答案相似但不完整,请发表评论,我会尽力帮助您。 :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM