Skip to content

Instantly share code, notes, and snippets.

@dsvoronin
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dsvoronin/44da0df59eeaa0c9fce1 to your computer and use it in GitHub Desktop.
Save dsvoronin/44da0df59eeaa0c9fce1 to your computer and use it in GitHub Desktop.
boxes for android
import com.squareup.picasso.Picasso;
import com.squareup.picasso.RequestCreator;
import java.io.File;
/**
* box for image we do not know exact type.
* it can be url, or res id
*/
public class Image {
private final Type type;
private final int resId;
private final String url;
private final File file;
private Image(Type type, int resId, String url, File file) {
this.type = type;
this.resId = resId;
this.url = url;
this.file = file;
}
public Image(int resId) {
this(Type.RES, resId, null, null);
}
public Image(String url) {
this(Type.URL, -1, url, null);
}
public Image(File file) {
this(Type.FILE, -1, null, file);
}
public Type getType() {
return type;
}
public int getResId() {
return resId;
}
public String getUrl() {
return url;
}
public File getFile() {
return file;
}
public RequestCreator load(Picasso picasso) {
switch (type) {
case URL:
return picasso.load(url);
case FILE:
return picasso.load(file);
case RES:
return picasso.load(resId);
default:
throw new IllegalArgumentException("Unknown type: " + type);
}
}
public enum Type {
URL, FILE, RES
}
}
import android.content.Context;
import android.support.annotation.Nullable;
import android.widget.TextView;
/**
* box for string we don't know exact type
*/
public class Label {
private final Type type;
private final int resId;
private final String s;
private Label(Type type, int resId, String s) {
this.type = type;
this.resId = resId;
this.s = s;
}
public Label(int resId) {
this.type = Type.RES;
this.resId = resId;
this.s = null;
}
public Label(String s) {
this.type = Type.PLAIN;
this.resId = -1;
this.s = s;
}
public Loader load(Context context) {
return new Loader(getString(context));
}
public String getString(Context context) {
switch (type) {
case RES:
return context.getString(resId);
case PLAIN:
return s;
default:
throw new IllegalStateException("Unknown type: " + type);
}
}
@Nullable
public String getString() {
return s;
}
public static class Loader {
private final String s;
public Loader(String s) {
this.s = s;
}
public void into(TextView textView) {
textView.setText(s);
}
}
public enum Type {
RES, PLAIN
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment