Question

I am having an issue of placing a imagebutton/imageview between a multiline textview in Android.

Eg.:

enter image description here

The text is dynamic. I am having many views like this in my application(nearly 50) with different texts and I want to achieve this with re-usability of code. So kindly suggest me some dynamic solution. On clicking the imagebutton/imageview, it should redirect to calling screen.

I am open to ideas of performing this with the help of WebViews unless and until they handle the dynamicity of text throughout the application(I don't want to make Html file for each and every view).

Looking for the sincere co-operation. Thank You.

Was it helpful?

Solution

Try this

        SpannableString string1=new SpannableString(yourdynamictext);

//Get Drawable
             Drawable d=getResources().getDrawable(R.drawable.ic_launcher);
        d.setBounds(0,0,d.getIntrinsicWidth(),d.getIntrinsicHeight());

// image span
        ImageSpan span2= new ImageSpan(d,ImageSpan.ALIGN_BASELINE);
            string1.setSpan(span2, 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
       yourtextview.setText(string1);

Update:

set this for your textview

yourtexview.setMovementMethod(LinkMovementMethod.getInstance());

Use ClickableSpan

Here is the example

 ClickableSpan clickableSpan = new ClickableSpan() {
                @Override
                public void onClick(View textView) {
                   Toast.makeText(MainActivity.this, "Hello",Toast.LENGTH_LONG).show();
                }
            };


           string1.setSpan(clickableSpan , 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
           yourtextview.setText(string1);

OTHER TIPS

You will need to set two spans: imagespan and ClickableSpan like this.

fun TextView.setIconifiedText(text: String, @DrawableRes iconResId: Int) {
    val clickableSpan: ClickableSpan = object : ClickableSpan() {
        override fun onClick(textView: View) {
            Log.d("", "onClick: ")
        }
    }
    SpannableStringBuilder("$text#").apply {
        setSpan(
            ImageSpan(context, iconResId, DynamicDrawableSpan.ALIGN_BOTTOM),
            text.length,
            text.length + 1,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        setSpan(clickableSpan, text.length, text.length + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
    }.let {
        setText(it)
        movementMethod = LinkMovementMethod.getInstance()
    }
}

Usage:

textView.setIconifiedText("your text", R.drawable.icon);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top