import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.ImageButton;
import android.widget.TableLayout;
import android.widget.TableRow;
public class LayoutDemo extends Activity {
private int viewWidth = 0;
private int viewHeight = 0;
private int buttonImageWidth = 75;
private Handler mHandler = new Handler();
String[] urlList = {
"http://farm1.static.flickr.com/23/24760921_bb7d2887d4_s.jpg",
"http://farm1.static.flickr.com/9/13482809_ff6b656dda_s.jpg",
"http://farm1.static.flickr.com/72/214374494_d34d1ab77c_s.jpg",
"http://farm1.static.flickr.com/120/281432030_ec8185d2f4_s.jpg",
"http://farm1.static.flickr.com/23/29766757_6417c1c308_s.jpg",
"http://farm1.static.flickr.com/10/13340408_9c3c2a7891_s.jpg",
"http://farm1.static.flickr.com/9/13465185_051396223a_s.jpg",
"http://farm1.static.flickr.com/21/25276474_1d7193486e_s.jpg",
"http://farm1.static.flickr.com/12/17668936_203a8690f7_s.jpg",
"http://farm1.static.flickr.com/46/193667084_0a152b5843_s.jpg",
"http://farm1.static.flickr.com/109/276274827_7e8e4f096b_s.jpg",
"http://farm1.static.flickr.com/10/13482804_6aac7b029b_s.jpg"
};
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
viewWidth = this.getResources().getDisplayMetrics().widthPixels;
viewHeight = this.getResources().getDisplayMetrics().heightPixels;
setContentView(R.layout.layout_demo);
mHandler.postDelayed(createImageGridTask, 100);
}
private Runnable createImageGridTask = new Runnable() {
public void run() {
createButtonGrid();
}
};
private void createButtonGrid() {
TableLayout grid = (TableLayout) findViewById(R.id.imageGrid);
int buttonId = 120;
int numColumns = (viewWidth / buttonImageWidth);
int colNum = 0;
TableRow row = new TableRow(this);
for (int i = 0; i < urlList.length; i++) {
try {
if (colNum == 0) {
row = new TableRow(this);
}
row.addView(
getImageButton(urlList[i], buttonId++),
new TableRow.LayoutParams()
);
Log.e(LayoutDemo.class.getName(), "add " + urlList[i]);
if (++colNum == numColumns || i == urlList.length - 1) {
Log.e(LayoutDemo.class.getName(), "add row");
grid.addView(row, new TableLayout.LayoutParams());
grid.postInvalidate();
grid.forceLayout();
colNum = 0;
}
} catch (MalformedURLException e) {
showAlert("MalformedURLException", e.getMessage() , "Ok", true);
} catch (IOException e) {
showAlert("IOException", e.getMessage() , "Ok", true);
}
}
}
private ImageButton getImageButton(String urlStr, int buttonId)
throws MalformedURLException, IOException {
ImageButton imgButton = new ImageButton(this);
imgButton.setId(buttonId);
URL url = new URL(urlStr);
HttpURLConnection urlConnection =
(HttpURLConnection) url.openConnection();
imgButton.setImageBitmap(
BitmapFactory.decodeStream(
urlConnection.getInputStream()
)
);
return imgButton;
}
}