I have to show text and images exactly as TextView holds. spannable object can be used but the problem is images are being downloaded from server at run time and have to display placeholder till images are downloaded..
So I am thinking of creating Custom TextView which extends a ViewGroup but then there would be a lot of handling. let me know if there is another best option available because I have shortage of time
This can be achieved by using SpannableString and ImageSpan classes. An instance of SpannableString can be created and can be set to TeaxtView.
Instance of SpannableString can contain combination of Text and Image. Here is a quick example I could find:
public class TestActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView textView = (TextView) findViewById(R.id.textview);
SpannableString ss = new SpannableString("abc");
Drawable d = getResources().getDrawable(R.drawable.icon32);
d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
ss.setSpan(span, 0, 3, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
textView.setText(ss);
}
Have a look at this link as well
I think the easiest way to achieve this is to create a custom TextView that inside uses Html.fromHtml() to add the images and the text. You can then feed it the placeholder and when the images load you simply update with the new image. You wouldn't need to handle almost anything.
The stuff you pass to the TextView could be something of the sort:
CustomTextView(String text, List<...> plceholders)
With the text containing string placeholders for where the images should be fitted, something like "{img} test message {img}" and then a simple search and replace for {img} with the <img> tag should be enough.
You can find plenty of samples online about Html.fromHtml().
Also, N-JOY's Spannable String solution would work.
Here is the solution I implemented.
Spanned spanned = null;
String messageCustomized = "<img src ='"+ WebConstant.IMAGE_BASE_URL +
part +"'/>";//WebConstant.IMAGE_BASE_URL + part;
Spanned span = Html.fromHtml(messageCustomized, new
URLImageParser(sentMessagesViewHolder.tvMessage, context), null);
if (spanned!=null) {
spanned = (Spanned) TextUtils.concat(spanned, span);
}else spanned= span;
if (spanned!=null) {
txtView.setText(spanned);
}
Image Getter
public class URLImageParser implements ImageGetter {
Context context;
View container;
private int imageSize = 20;
private int imageSizeDisplaySize = 20;
URLDrawable urlDrawable = null;
public URLImageParser(View container, Context context) {
this.context = context;
this.container = container;
imageSize = Utility.convertDpTopPixels(context, 20);
imageSizeDisplaySize = Utility.convertDpTopPixels(context, 35);
}
#Override
public Drawable getDrawable(final String url) {
String[] arr = url.split("/");
final String fileName = arr[arr.length - 1];
urlDrawable = new URLDrawable();
Drawable drawable = null;
if (Build.VERSION.SDK_INT >= 21)
drawable =
context.getDrawable(R.drawable.profile_main_placeholder);
else
drawable = context.getResources().getDrawable(R.drawable.profile_main_placeholder);
drawable.setBounds(0, 0, 0 + imageSize, 0 + imageSize);
urlDrawable.drawable = drawable;
Bitmap bitmap = null;
bitmap = ImageUtility.getImageFromSDCard(fileName);
if (bitmap != null) { // the bitmap is available
bitmap = RoundedImageView.getCroppedBitmap(bitmap, imageSize, imageSize, imageSize);
drawable = new BitmapDrawable(context.getResources(), bitmap);//ImageUtility.bitmapToDrawable(context,resource);
drawable.setBounds(0, 0, 0 + imageSize, 0 + imageSize); //set the correct bound according to the result from HTTP call
URLImageParser.this.urlDrawable.drawable = drawable;
} else
Glide.with(context)
.load(url)
.asBitmap()
.transform(new CircleTransform(context))
.override(imageSizeDisplaySize, imageSizeDisplaySize)
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
// you can do something with loaded bitmap here
// .....
Drawable drawable = new BitmapDrawable(context.getResources(), resource);//ImageUtility.bitmapToDrawable(context,resource);
drawable.setBounds(0, 0, 0 + imageSize, 0 + imageSize); //set the correct bound according to the result from HTTP call
URLImageParser.this.urlDrawable.drawable = drawable;
URLImageParser.this.container.invalidate();
ImageUtility.saveImageToSDCard(resource, fileName);
}
});
return urlDrawable.drawable; //return reference to URLDrawable where We will change with actual image from the src tag
//}
}
}
Custom Bitmap Drawable
public class URLDrawable extends BitmapDrawable {
// the drawable that you need to set, you could set the initial drawing
// with the loading image if you need to
protected Drawable drawable;
#Override
public void draw(Canvas canvas) {
// override the draw to facilitate refresh function later
if(drawable != null) {
drawable.draw(canvas);
}
}
}
Related
i've been searching but got no results on adding custom images as emoji in android application.Thank you for any kind of help
Here is my problem :
I've trying to do a custom keyboard in android which includes only custom images as emoji,i manage to show image in keyboard but when i try to send it ,i get [OBJ] in return.
Here is some of my code , i tried many possible ways ;
String s = "<img src='a.png'/>";
// Spanned cs = Html.fromHtml("<img src='" + getResources().getDrawable(R.drawable.a) + "'/>", imageGetter, null);
/* ic.commitText( Html.fromHtml(s, new Html.ImageGetter() {
#Override public Drawable getDrawable(String source) {
Drawable drawFromPath;
int path =
emoji.this.getResources().getIdentifier(source, "drawable",
"com.cmosteknoloji.emoji");
drawFromPath = (Drawable) emoji.this.getResources().getDrawable(path);
drawFromPath.setBounds(0, 0, drawFromPath.getIntrinsicWidth(),
drawFromPath.getIntrinsicHeight());
return drawFromPath;
}
}, null),1);*/
Spanned spanned = Html.fromHtml(s, this, null);
ic.commitText(spanned,1);
#Override
public Drawable getDrawable(String arg0) {
// TODO Auto-generated method stub
int id = 0;
if(arg0.equals("a.png")){
id = R.drawable.a;
}
LevelListDrawable d = new LevelListDrawable();
Drawable empty = getResources().getDrawable(id);
d.addLevel(0, 0, empty);
d.setBounds(0, 0, empty.getIntrinsicWidth(), empty.getIntrinsicHeight());
return d;
}
ImageGetter imageGetter = new ImageGetter() {
#Override
public Drawable getDrawable(String source) {
byte [] encodeByte=Base64.decode("iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==",Base64.DEFAULT);
Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
Drawable d = new BitmapDrawable(bitmap);
Log.e("Chk", "Height : "+d.getIntrinsicHeight());
Log.e("Chk", "Width : " + d.getIntrinsicWidth());
return d;
}
};
I have a list adapter to show content frm my social network, i need to put inside the text the img tags, i've tried using Html.fromhtml and it's formatting the text but instead of shows the img it shows a gray square.
How can i achieve that? I'v read about ImageGetter but i still don't have it very clear.
Thanks
You can draw an Image in TextView using the Html img tag with Html.ImageGetter. But make sure your image is available in resource drawable folder
Here is a sample , The image will be loaded from the resource.
String htmlText = "Hai <img src=\"ic_launcher\"> Hello";
textView.setText(Html.fromHtml(htmlText, new Html.ImageGetter() {
#Override
public Drawable getDrawable(String source) {
int resourceId = getResources().getIdentifier(source, "drawable",getPackageName());
Drawable drawable = getResources().getDrawable(resourceId);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
return drawable;
}
}, null));
String mIsi = (String) bundle.get("isi");
isi.setText(Html.fromHtml(mIsi, new Html.ImageGetter() {
#Override
public Drawable getDrawable(final String source) {
Picasso.get()
.load(source).into(imageView, new Callback() {
#Override
public void onSuccess() {
drawable = imageView.getDrawable();
drawable.setBounds(0, 0,
drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight());
}
#Override
public void onError(Exception e) {
Log.v("test pic","err"+e.getMessage());
}
});
imageView.setVisibility(View.GONE);
return drawable;
}
}, null));
Continuing from my previous post, I was able to set multiple elements to the MultiAutoCompleteTextView but I was not able to wrap those items with custom background and close button as in that link picture.
I was able to do the same with single element but for multiple, ran out of luck.
This is what I tried.
// set text to MultiAutoCompleteTextView
private void setTextSample(String contactName) {
final SpannableStringBuilder sb = new SpannableStringBuilder();
TextView tv = (TextView) LayoutInflater.from(this).inflate(R.layout.textview, null);
tv.setText(contactName);
BitmapDrawable bd = (BitmapDrawable) convertViewToDrawable(tv);
bd.setBounds(0, 0, bd.getIntrinsicWidth(), bd.getIntrinsicHeight());
sb.append(contactName + ",");
sb.setSpan(new ImageSpan(bd), sb.length()-(contactName.length()+1),
sb.length()-1,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
mMultiAutoCompleteTextView.setText(sb);
}
// wrap text with custom elements
private static Object convertViewToDrawable(View view) {
int spec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
view.measure(spec, spec);
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
Bitmap b = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(),
Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
c.translate(-view.getScrollX(), -view.getScrollY());
view.draw(c);
view.setDrawingCacheEnabled(true);
Bitmap cacheBmp = view.getDrawingCache();
Bitmap viewBmp = cacheBmp.copy(Bitmap.Config.ARGB_8888, true);
view.destroyDrawingCache();
return new BitmapDrawable(viewBmp);
}
Any help is greatly appreciated.
Edit :
If I do
mMultiAutoCompleteTextView.setText(mMultiAutoCompleteTextView.getText().toString()+", "+sb);
I am getting multiple texts but they are not wrapped with custom background.
Not getting where I am going wrong.
Edit :
Sample multiple elements would look something like this
try this:
class MyMultiAutoCompleteTextView extends MultiAutoCompleteTextView {
public MyMultiAutoCompleteTextView(Context context) {
super(context);
}
#Override
protected void replaceText(CharSequence text) {
Log.d(TAG, "replaceText " + text.getClass() + " " + text);
super.replaceText(getSpanned(text.toString()));
}
}
private Spanned getSpanned(String name) {
TextView tv = (TextView) LayoutInflater.from(this).inflate(R.layout.test, null);
tv.setText(name);
SpannableStringBuilder sb = new SpannableStringBuilder(name);
sb.setSpan(new ViewReplacementSpan(tv), 0, sb.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return sb;
}
class ViewReplacementSpan extends DynamicDrawableSpan {
private View v;
private Drawable drawable;
public ViewReplacementSpan(View v) {
super(ALIGN_BOTTOM);
this.v = v;
int spec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
v.measure(spec, spec);
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
drawable = new SpanDrawable();
drawable.setBounds(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
}
#Override
public Drawable getDrawable() {
return drawable;
}
class SpanDrawable extends Drawable {
#Override
public void draw(Canvas canvas) {
canvas.clipRect(getBounds());
v.draw(canvas);
}
#Override
public void setAlpha(int alpha) {
}
#Override
public void setColorFilter(ColorFilter cf) {
}
#Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
}
}
test it with the following in onCreate():
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
MultiAutoCompleteTextView mactv = new MyMultiAutoCompleteTextView(this);
ArrayAdapter<Spanned> a = new ArrayAdapter<Spanned>(this, android.R.layout.simple_dropdown_item_1line);
String[] names = { "Jane", "John", "Mary", "Mark" };
for (String name: names) {
a.add(getSpanned(name));
}
Tokenizer tokenizer = new MultiAutoCompleteTextView.CommaTokenizer();
mactv.setTokenizer(tokenizer);
mactv.setAdapter(a);
mactv.setThreshold(1);
SpannableStringBuilder sb = new SpannableStringBuilder();
for (int i = 0; i < 2; i++) {
sb.append(tokenizer.terminateToken(a.getItem(i)));
}
mactv.setText(sb);
ll.addView(mactv);
TextView tv = new TextView(this);
tv.setGravity(Gravity.CENTER);
tv.setText("try: Jane, John, Mary or Mark");
tv.setTextSize(32);
ll.addView(tv);
setContentView(ll);
I think you have problem here:
mMultiAutoCompleteTextView.setText(mMultiAutoCompleteTextView.getText().toString()+", "+sb);
When you call mMultiAutoCompleteTextView.getText().toString(), you convert your spannableString to ordinary string, which can't hold background or smth else.
Try to save your current SpannableStringBuilder somewhere and work like that:
mBuilder.append(sb);
mMultiAutoCompleteTextView.setText(mBuilder);
I have a custom view with a lot of png images on it(For every three characters an image). but it is too slow on drawing and scrolling.
It is my code for custom view:
public class Textview extends View
{
private String m_szText;
Context ctx;
Paint mTextPaint;
private Canvas canva;
Bitmap b ;
public Textview(Context context)
{
super(context);
ctx = context;
mTextPaint= new Paint();
mTextPaint.setTypeface(m_tTypeface);
mTextPaint.setStyle(Paint.Style.FILL);
}
public void SetText(String newtext) {
m_szText = newtext;
text(newtext);
this.invalidate();
}
#Override
protected void onDraw(Canvas canvas)
{
super.onDraw(text(canvas,m_szText));
}
Canvas text(Canvas canvas,String txt)
{
int left = 400;
int top = 0;
try {
for(int i=0;i<txt.length();i=i+3)
{
String adres = "glyph/" + txt.substring(i, i+3) + ".png";
Bitmap btm = getBitmapFromAsset(adres);
if(left <= 5)
{left = 400;top += btm.getHeight();}
else
left = left - btm.getWidth();
canvas.drawBitmap(btm, left ,top,mTextPaint);
}
} catch (IOException e) {
canvas.drawText(e.toString(), 50, 50, mTextPaint);
}
return canvas;
}
private Bitmap getBitmapFromAsset(String strName) throws IOException
{
AssetManager assetManager = ctx.getAssets();
InputStream istr = assetManager.open(strName);
Bitmap bitmap = BitmapFactory.decodeStream(istr);
return bitmap;
}
}
How can I speed up my custom view? I think I must to create bitmap of all images once. but how to?
thanks in advance!
You are loading and decoding several bitmaps on every draw. You need to load the bitmaps ahead of time, once and then draw them.
You can use Thread to speed up process, and there are two way to use thread
1)Implementing Runnable that override void run(){}
2)or use Thread th=new Thread(new Runnable(){void run(){}
})
The following should help. just outline of what can be done.
static HashMap<String, Bitmap> mBitmaps = new HashMap<String, Bitmap>();
public void SetText(String newtext) {
m_szText = newtext;
makeBitmap();
this.invalidate();
}
void makeBitmap()
{
for(int i=0; i<m_szText.length(); i=i+3)
{
String adres = "glyph/" + m_szText.substring(i, i+3) + ".png";
Bitmap btm = null;
if (!mBitmaps.containsKey(adres)) {
btm = getBitmapFromAsset(adres);
mBitmaps.add(adres , btm);
} else {
btm = (Bitmap)mBitmaps.get(adres);
}
length += btm.getWidth(); // considering only single line.
}
// create a new blank Bitmap of height and 'length' and assign to member.
mTextBitmap = Bitmap.createBitmap(length, height, Bitmap.Config.ARGB_8888);
// in for loop draw all the bitmaps on mTextBitmap just like you did on canvas in ur code.
}
I want to set a TextView with SpannableString which is from the method below:
Html.fromHtml(String source, Html.ImageGetter imageGetter,
Html.TagHandler tagHandler)
But the ImageGetter here need to override the method below:
public abstract Drawable getDrawable(String source)
Because I need to get the drawable from the internet, I have to do it asynchronously and seems it is not.
How to make it work?
Thanks.
These guys did a great job, this is my solution using Square's Picasso library:
//...
final TextView textView = (TextView) findViewById(R.id.description);
Spanned spanned = Html.fromHtml(getIntent().getStringExtra(EXTRA_DESCRIPTION),
new Html.ImageGetter() {
#Override
public Drawable getDrawable(String source) {
LevelListDrawable d = new LevelListDrawable();
Drawable empty = getResources().getDrawable(R.drawable.abc_btn_check_material);;
d.addLevel(0, 0, empty);
d.setBounds(0, 0, empty.getIntrinsicWidth(), empty.getIntrinsicHeight());
new ImageGetterAsyncTask(DetailActivity.this, source, d).execute(textView);
return d;
}
}, null);
textView.setText(spanned);
//...
class ImageGetterAsyncTask extends AsyncTask<TextView, Void, Bitmap> {
private LevelListDrawable levelListDrawable;
private Context context;
private String source;
private TextView t;
public ImageGetterAsyncTask(Context context, String source, LevelListDrawable levelListDrawable) {
this.context = context;
this.source = source;
this.levelListDrawable = levelListDrawable;
}
#Override
protected Bitmap doInBackground(TextView... params) {
t = params[0];
try {
Log.d(LOG_CAT, "Downloading the image from: " + source);
return Picasso.with(context).load(source).get();
} catch (Exception e) {
return null;
}
}
#Override
protected void onPostExecute(final Bitmap bitmap) {
try {
Drawable d = new BitmapDrawable(context.getResources(), bitmap);
Point size = new Point();
((Activity) context).getWindowManager().getDefaultDisplay().getSize(size);
// Lets calculate the ratio according to the screen width in px
int multiplier = size.x / bitmap.getWidth();
Log.d(LOG_CAT, "multiplier: " + multiplier);
levelListDrawable.addLevel(1, 1, d);
// Set bounds width and height according to the bitmap resized size
levelListDrawable.setBounds(0, 0, bitmap.getWidth() * multiplier, bitmap.getHeight() * multiplier);
levelListDrawable.setLevel(1);
t.setText(t.getText()); // invalidate() doesn't work correctly...
} catch (Exception e) { /* Like a null bitmap, etc. */ }
}
}
My 2 cents... Peace!
Now I'm using an AsyncTask to download the images in the ImageGetter:
Spanned spannedContent = Html.fromHtml(htmlString, new ImageGetter() {
#Override
public Drawable getDrawable(String source) {
new ImageDownloadAsyncTask().execute(textView, htmlString, source);
return null;
}
}, null);
And set the text again into the TextView when the image has been downloaded.
Now it works. But It failed when I tried to do the TextView.postInvalidate() to redraw the downloaded images. I have to do setText() again in the AsyncTask.
Does anyone know why?
Here's my code that grabs all images in the html string (it's simplified from the original, so I hope it works):
private HashMap<String, Drawable> mImageCache = new HashMap<String, Drawable>();
private String mDescription = "...your html here...";
private void updateImages(final boolean downloadImages) {
if (mDescription == null) return;
Spanned spanned = Html.fromHtml(mDescription,
new Html.ImageGetter() {
#Override
public Drawable getDrawable(final String source) {
Drawable drawable = mImageCache.get(source);
if (drawable != null) {
return drawable;
} else if (downloadImages) {
new ImageDownloader(new ImageDownloader.ImageDownloadListener() {
#Override
public void onImageDownloadComplete(byte[] bitmapData) {
Drawable drawable = new BitmapDrawable(getResources(),
BitmapFactory.decodeByteArray(bitmapData, 0, bitmapData.length));
try {
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
} catch (Exception ex) {}
mImageCache.put(source, drawable);
updateImages(false);
}
#Override
public void onImageDownloadFailed(Exception ex) {}
}).execute(source);
}
return null;
}
}, null);
tvDescription.setText(spanned);
}
So basically what happens here is the ImageGetter will make a request for every image in the html description. If that image isn't in the mImageCache array and downloadImages is true, we run an async task to download that image. Once it has completed, we add the drawable into the hashmap, and then make a call to this method again (but with downloadImages as false so we don't risk an infinite loop), where the image will be able to be grabbed with the second attempt.
And with that, you'll need the ImageDownloader class that I used:
public class ImageDownloader extends AsyncTask {
public interface ImageDownloadListener {
public void onImageDownloadComplete(byte[] bitmapData);
public void onImageDownloadFailed(Exception ex);
}
private ImageDownloadListener mListener = null;
public ImageDownloader(ImageDownloadListener listener) {
mListener = listener;
}
protected Object doInBackground(Object... urls) {
String url = (String)urls[0];
ByteArrayOutputStream baos = null;
InputStream mIn = null;
try {
mIn = new java.net.URL(url).openStream();
int bytesRead;
byte[] buffer = new byte[64];
baos = new ByteArrayOutputStream();
while ((bytesRead = mIn.read(buffer)) > 0) {
if (isCancelled()) return null;
baos.write(buffer, 0, bytesRead);
}
return new AsyncTaskResult<byte[]>(baos.toByteArray());
} catch (Exception ex) {
return new AsyncTaskResult<byte[]>(ex);
}
finally {
Quick.close(mIn);
Quick.close(baos);
}
}
protected void onPostExecute(Object objResult) {
AsyncTaskResult<byte[]> result = (AsyncTaskResult<byte[]>)objResult;
if (isCancelled() || result == null) return;
if (result.getError() != null) {
mListener.onImageDownloadFailed(result.getError());
}
else if (mListener != null)
mListener.onImageDownloadComplete(result.getResult());
}
}