title: Android: GridLayout not refreshed after dynamically updating child ImageButtons
body: <p>I'm having trouble figuring out how I can get my GridLayout to consistently update the UI on the screen when I dynamically add/remove ImageButtons in it. I've tried adding <code>invalidate()</code>, <code>requestLayout</code> <code>refreshDrawableState</code> and the visibility trick (switching from <code>GONE</code> to <code>VISIBLE</code> again) suggested in other answers, but no can do.</p>
  
  <p>Here's the relevant code inside my Activity:</p>
  
  <pre><code>DataInputStream data = new DataInputStream(btSocket.getInputStream());
  while (true) {
     readImage("1"); // adds one image button
     readImage("2"); // adds one image button
     readImage("3"); // adds one image button
    }
  });
  </code></pre>
  
  <p>The above code is run inside a separate thread that listens for image data being sent over a BlueTooth connection. The <code>readImage</code> calls block until data is received (images are sent in batches of 3) with the first call clearing all the existing buttons if there are any.</p>
  
  <p>The <code>readImage</code> method contains the following code to add ImageButtons to the GridLayout when images are received via <code>runOnUiThread</code> or <code>imageGridLayout.post</code> (I tried both, same result).</p>
  
  <pre><code>runOnUiThread(new Runnable() {
     @Override
     public void run() {
        Button but = new Button(this);
        // Set different images for pressed and normal states
        StateListDrawable states = new StateListDrawable();
        states.addState(new int[] { },new BitmapDrawable(getResources(), bmp));
        states.addState(new int[] {android.R.attr.state_pressed},new BitmapDrawable(getResources(), modifiedBmp));
        but.setBackground(states);
        [...] // set various layout parameters
        but.setOnClickListener(buttonlistener);
        imageGridLayout.addView(but);
     }
  });
  </code></pre>
  
  <p>Currently only two buttons are shown each time a batch is received, even though the GridLayout does contain three children. The third ImageButton is never shown on the screen. Besides, the button click listener and the state changes don't work.</p>
  
  <p>If I manually populate the GridLayout with dummy ImageButtons inside the main thread of the Activity the buttons are shown and work perfectly.</p>
  
  <p>This requirement to call <code>runOnUiThread</code> or <code>imageGridLayout.post</code> to change the UI is killing me. What's the solution?</p>