Android: Hey, I want to get the width of the screen and divide it by 3. I want to use this length in LayoutParams, but it does not work. What am I doing wrong? Application crashes when // 1.
public class LoaderImageView extends LinearLayout {
private Context mContext;
private Drawable mDrawable;
private ProgressBar mSpinner;
private ImageView mImage;
Context ctx;
Display display;
public LoaderImageView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public LoaderImageView(Context context) {
super(context);
init(context);
}
private void init(final Context context) {
mContext = context;
//1. // it was an application crash, hence
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
//here
mImage = new ImageView(mContext);
mImage.setLayoutParams(new LayoutParams((width/3), 150));
mImage.setVisibility(View.GONE);
mImage.setBackgroundColor(Color.WHITE);
mImage.setPadding(3, 3, 3, 3);
mSpinner = new ProgressBar(mContext);
mSpinner.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
mSpinner.setIndeterminate(true);
addView(mSpinner);
addView(mImage);
}
public void setImageDrawable(final String imageUrl) {
mDrawable = null;
mSpinner.setVisibility(View.VISIBLE);
mImage.setVisibility(View.GONE);
new Thread() {
public void run() {
try {
mDrawable = getDrawableFromUrl(imageUrl);
imageLoadedHandler.sendEmptyMessage(RESULT_OK);
} catch (MalformedURLException e) {
imageLoadedHandler.sendEmptyMessage(RESULT_CANCELED);
} catch (IOException e) {
imageLoadedHandler.sendEmptyMessage(RESULT_CANCELED);
}
};
}.start();
}
private final Handler imageLoadedHandler = new Handler(new Callback() {
public boolean handleMessage(Message msg) {
switch (msg.what) {
case RESULT_OK:
mImage.setImageDrawable(mDrawable);
mImage.setVisibility(View.VISIBLE);
mSpinner.setVisibility(View.GONE);
break;
case RESULT_CANCELED:
default:
break;
}
return true;
}
});
private static Drawable getDrawableFromUrl(final String url) throws IOException, MalformedURLException {
return Drawable.createFromStream(((java.io.InputStream) new java.net.URL(url).getContent()), "name");
}
}
source
share