1.activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#e6e6e6"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
2.MainActivity.java
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Selection;
import android.text.Spannable;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ImageSpan;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textView = (TextView) findViewById(R.id.textView);
String text = "Image $ span";
int $index = text.indexOf("$");
Spannable span = Spannable.Factory.getInstance().newSpannable(text);
span.setSpan(new ImageSpan(getBaseContext(), android.R.drawable.star_on),
$index, $index + 1,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//for on image click
span.setSpan(new ClickableSpan() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Image is clicked", Toast.LENGTH_SHORT).show();
}
}, $index, $index + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(span);
//for image clickable
textView.setMovementMethod(new LinkMovementMethod() {
@Override
public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
Selection.removeSelection(buffer);
widget.setHighlightColor(Color.argb(0,0,0,0));
return super.onTouchEvent(widget, buffer, event);
}
});
}
}
1 comments so far
Thanks a lot it really helped me with ImageSpan
EmoticonEmoticon