Search code examples
androidviewandroid-inflate

Inflation of View Failing


I've been trying to programatically inflate a linearlayout of buttons using a loop, but it doesn't show up in the ui at all. The array gets populated, however.

My button xml:

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

My style resource:

<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>

My initialization code:

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);

Solution

  • So I went ahead and tried the code you provided using Android Studio and I have also received a blank screen. Main point that I saw that caused this is in your BlackKey style, the layout_weight is provided, the layout_height is set to 0dp, and the layout_width is MATCH_PARENT, but the orientation is horizontal -- if ever the button shows up, this will make it only show a single button.

    If how I understood on how you want this to show up (five buttons alongside each other in horizontal orientation, with equal widths) something like this:

    enter image description here

    Then you can just modify the BlackKey styles like this:

    <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>
    

    And also a tip, if ever you're using Android Studio, you can check first if the Button is showing in the Design Tab to see if it shows up properly on the screen. If it doesn't show up there, then try to modify it. Hope this helps you. If you have further questions, or if this is similar to the answer you're looking for but is not complete, just post a comment and I'll try to help you out. :)