Underline a dynamically generated TextView in android - android

I have a text view which has a certain text which is set in the xml file and in the strings.xml it is underlined.Now i am changing this textview form the contents in the edittext,i.e whatever the user is entering.To that text before setting it to the textview i am appending acertain string as well.I want this new string formed to be underlined with blue color and clickable. I tried using
SpannableString phoneNum = new SpannableString(totalPhoneNum);
phoneNum.setSpan(new UnderlineSpan(), 0, totalPhoneNum.length(), 0);
phoneNum.setText(totalPhoneNum);
This is not working! Can i use this in onResume()
I have no idea how to change the color of the underline to blue :(

There are three ways of underling the text in TextView.
SpannableString
setPaintFlags(); of TextView
Html.fromHtml();
Let me explain you all approaches :
1st Approach
For underling the text in TextView you have to use SpannableString
String udata="Underlined Text";
SpannableString content = new SpannableString(udata);
content.setSpan(new UnderlineSpan(), 0, udata.length(), 0);
mTextView.setText(content);
2nd Approach
You can make use of setPaintFlags method of TextView to underline the text of TextView.
For eg.
mTextView.setPaintFlags(mTextView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
mTextView.setText("This text will be underlined");
You can refer constants of Paint class if you want to strike thru the text.
3rd Approach
Make use of Html.fromHtml(htmlString);
String htmlString="<u>This text will be underlined</u>";
mTextView.setText(Html.fromHtml(htmlString));
From:
To draw an Underline below the TextView in Android

You can use like this
phoneNum.setText(Html.fromHtml("W : "+"<u><FONT COLOR=\"#80776b\" >"+Your text+"</Font></u>"));
Use color code what you want.

Use this:
String text = "some string <u><font color=\"#00FF00\">some link</font></u>";
editText.setText(Html.fromHtml(text), TextView.BufferType.SPANNABLE);

try with this
String txt = "<u style=\"text-decoration: none; border-bottom: 1px solid #FF0000\">parragraph</u>";
phoneNum.setText(Html.fromHtml(txt));
this style will remove default underline and put a border bottom of 1 px as of color we pass.

xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="#string/hello" />
</LinearLayout>
java:
public class TextDemoActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new ViewWithRedDot(this));
}
}
class ViewWithRedDot extends View {
public ViewWithRedDot(Context context) {
super(context);
}
#Override
protected void onDraw(Canvas canvas) {
Paint circlePaint = new Paint();
Typeface mType = Typeface.create(Typeface.SANS_SERIF, Typeface.ITALIC);
circlePaint.setTextSize(25);
circlePaint.setColor(Color.RED);
circlePaint.setTypeface(mType);
canvas.drawText("Default Typeface", 50, 100, circlePaint);
//
circlePaint.setFlags(Paint.UNDERLINE_TEXT_FLAG);
circlePaint.setColor(Color.YELLOW);
canvas.drawText("Underline Text Flag", 50, 120, circlePaint);
//
circlePaint.setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
circlePaint.setColor(Color.GREEN);
canvas.drawText("Strike Thru Text Flag", 50, 140, circlePaint);
//
circlePaint.setFlags(Paint.ANTI_ALIAS_FLAG);
circlePaint.setColor(Color.WHITE);
canvas.drawText("Anti Alias Flag", 50, 160, circlePaint);
//
circlePaint.setFlags(Paint.DEV_KERN_TEXT_FLAG);
circlePaint.setColor(Color.WHITE);
canvas.drawText("Dev Kern Text Flag", 50, 180, circlePaint);
//
circlePaint.setFlags(Paint.FAKE_BOLD_TEXT_FLAG);
circlePaint.setColor(Color.CYAN);
canvas.drawText("Fake Bold Text Flag", 50, 200, circlePaint);
}
}

Add the following code in your layout xml file:
<TextView
android:autoLink="phone"
android:linksClickable="true"
android:textColorLink="#5e9baa" />

Related

Adding multiple smiles in TextView using ImageSpan

I am trying to add multiple smiles in textview using this code.
This is my TextView.
<TextView
android:id="#+id/textViewId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:bufferType="spannable" />
And this is add smiley function.
public void addSmily() {
int resource = R.drawable.smily ;
Spannable spannable = Spannable.Factory.getInstance().newSpannable(" ");
Drawable d = ContextCompat.getDrawable(this, resource);
d.setBounds(0, 0, 40, 40);
ImageSpan smilySpan = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
spannable.setSpan(smilySpan, spannable.length()-1, spannable.length(), 0);
sendText.append(spannable);
}
Smiles are adding perfectly but the problem is when I add lots of smiles did not fit in a single line then the first line of smiles become invisible and they start from the 2nd line.
This is what happening. Plz, someone help me.
Solution:
Try this inside your button:
SpannableString ss = new SpannableString("abc");
Drawable d = ContextCompat.getDrawable(your_activity.this, R.drawable.your_smiley_drawable);
d.setBounds(0, 0, 40, 40);
ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
ss.setSpan(span, 0, 3, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
edittext.append(ss);
Note: Also, EditText's inputtype must be textMultiline.
Try it, Works in my lap, Let's Hope it helps to you too.
You can also set smiley by unicode in textview.
how set emoji by unicode in a textview?
int unicode = 0x1F60A;
Which can be used with
public String getEmojiByUnicode(int unicode){
return new String(Character.toChars(unicode));
}
So Textview displays 😊 without Drawable
Try it with http://apps.timwhitlock.info/emoji/tables/unicode
Hope it may help you.

PagerTabStrip is clipping off the icon

The design called for just icon on the tab of the PagerTabStrip.
Here's the XML:
<android.support.v4.view.PagerTabStrip
android:id="#+id/tbstrp_album"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:foregroundGravity="bottom"
android:padding="0dp"
android:background="#color/offWhite">
Here's my getPageTitle inside the adapter:
#Override
public CharSequence getPageTitle(int position) {
// This is "generic" string that we will use as the title to be replaced.
String title = "title";
Drawable myDrawable = oContext.getDrawable(R.drawable.alpha);
// initiate the SpannableString builder
SpannableStringBuilder spanBuilder = new SpannableStringBuilder(title); // space added before text for convenience
// set the drawable's size...if it could be too big or too small for display
myDrawable.setBounds(0, 0, 50, 50);
// turn the Drawable into ImageSpan and align it along the baseline
ImageSpan imageSpan = new ImageSpan(myDrawable, ImageSpan.ALIGN_BASELINE);
// CRUCIAL: this is where we replace the "title" w/ the image
// 0: we start from the beginning
// title.length(): we are replacing the entire string
// the last flag doesn't do anything in our case
spanBuilder.setSpan(imageSpan, 0, title.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
return spanBuilder;
}
The output looks like this:
What's causing the strip clipping the image? Thanks!
It turns out this statement is the culprit:
myDrawable.setBounds(0, 0, 50, 50);
I changed the second argument which is the "top" to 30 and the icon was not clipped.
The unanswered question is still...why do I have to specify a value for the "top" argument.

ImageSpan Size Measurement with TextView and StaticLayout

I have a simple layout contains just one TextView.
I wanna load an image into TextView using ImageSpan.
Below method creates Spannable:
private Spannable getImageSpannable(int drawableId, int targetWidth, int targetHeight) {
Bitmap originalBitmap = BitmapFactory.decodeResource(getResources(), drawableId);
Bitmap bitmap = Bitmap.createScaledBitmap(originalBitmap, targetWidth, targetHeight, true);
Drawable dr = new BitmapDrawable(getResources(), bitmap);
dr.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());
Spannable imageSpannable = new SpannableString("\uFFFC");
ImageSpan imgSpan = new ImageSpan(dr, DynamicDrawableSpan.ALIGN_BOTTOM);
imageSpannable.setSpan(imgSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return imageSpannable;
}
I use this method to create content like this:
public void setContent() {
SpannableStringBuilder content = new SpannableStringBuilder();
content.append(getImageSpannable(R.drawable.my_image, 100, 260));
content.append("\n");
txtContent.setText(content);
}
When I call setContent() method my result is something like this:
As you see there is small gap between ImageSpan and top of TextView.
This is not line spacing, because I set line spacing to 0.
And interesting point is when I remove "\n" from content(declared in setContent method) this space is gone.
And another point is that when I tried to measure content size using StaticLayout, with "\n" at the end bottom of line 0 it returns 270 and without "\n" it returns 260.
This behavior causes some difficulties for me, because I have to measure text and ImageSpan using StaticLayout and decide witch one can fit into TextView.
I appreciate everyone can help me.
Thanks.
Here's my xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/txtContent"
android:layout_width="300dp"
android:layout_height="500dp"
android:background="#fed9f4"
android:textSize="22sp"/>
</LinearLayout>
I'v done some tests and I find that font size is affects ImageSpan rendering.
Can somebody explain this affect please?
I hope this method works
The following line of code
public void setContent() {
SpannableStringBuilder content = new SpannableStringBuilder();
content.append(getImageSpannable(R.drawable.my_image, 100, 260));
content.append("\n");
txtContent.setText(content);
}
Change to
public void setContent() {
SpannableStringBuilder content = new SpannableStringBuilder();
content.append(getImageSpannable(R.drawable.my_image, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
content.append("\n");
txtContent.setText(content);
}
And resize "R.drawable.my_image" dimensions

Different textcolors in the same textview

in my application i have to show some informations.i would structured these informations like this
Battery level //red textcolor
80% // black textcolor
Is it possible? Because for now i have created two separated textview; one for the "title" and another for the information with different colors. Thanks
You can use Spannable to achieve what you want:
TextView textView = (TextView) findViewById(R.id.textView);
String text = "<font color='red'>Battery level</font> <font color='black'>80%</font>"
textView.setText(Html.fromHtml(text), TextView.BufferType.SPANNABLE);
You can use SpannableString to overcome your issue.
Here is what you can do with your textviews
TextView tc_text = (TextView) findViewById(R.id.signup_TC_text);
SpannableString text = new SpannableString("Points are awarded when you confirm your email. By signing up, you agree to our Terms & Conditions.");
text.setSpan(new ForegroundColorSpan(Color.BLACK), 0, 80, 0);
final Context context = this;
ClickableSpan clickableSpan = new ClickableSpan() {
#Override
public void onClick(View view) {
}
};
text.setSpan(clickableSpan, 80, 98, 0);
// make our ClickableSpans and URLSpans work
tc_text.setMovementMethod(LinkMovementMethod.getInstance());
// shove our styled text into the TextView
tc_text.setText(text, BufferType.SPANNABLE);
Here what I have done is, I have counted number of characters from where to where I want some particular color.
Hope this will help you.

Is it possible to display multi-color text with one call to Canvas.drawText()?

I would like to use Canvas.drawText() to display multi-color text. More specifically, I want to highlight a substring of the text passed to the drawText() method.
The text is in the form of a SpannableString with 0 or more ForegroundColorSpan objects.
Looking at the Canvas code, it appears that a .toString() call on the passed CharSequence, means that this is not possible.
Is there an alternative way?
EDIT: The text may occasionally change (total changes, not incremental). Also, there are potentially multiple texts positioned in different unrelated locations in the custom view.
Yes it is possible by using one of the Layout classes. These are helper classes for drawing text to a canvas and they support Spannables. If your text doesn't change use a StaticLayout.
Example
Add this to your custom view class
private StaticLayout layout;
put this code into your onLayout or onSizeChanged
Spannable wordtoSpan = new SpannableString("I know just how to whisper, And I know just how to cry,I know just where to find the answers");
wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
TextPaint paint = new TextPaint();
paint.setTextSize(20f);
paint.setColor(Color.RED);
layout = new StaticLayout(wordtoSpan, paint, getWidth(), Alignment.ALIGN_NORMAL, 1, 0, false);
Then in your drawing method simply call
layout.draw(canvas);
In case your text changes often you can use a DynamicLayout.
Editable.Factory fac = Editable.Factory.getInstance();
Editable edit = fac.newEditable(wordtoSpan);
DynamicLayout layout = new DynamicLayout(edit,paint,getWidth(),Alignment.ALIGN_CENTER,1,0,false);
change text by using the edit object
edit.append("hello");
Try something like this, if you use TextView
String multiColorText = "<font color=0xff0000>Multi</font><font color=0x000000>Color</font><font color=0xccffff>Text</font>";
textView.setText(Html.fromHtml(multiColorText));
Edit :
For SpannableString, check if the below helps you
Spannable WordtoSpan = new SpannableString("partial colored text");
WordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 2, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Whenever you write that text for that view you can set thatView.setBackgroundResource(R.drawable.multicolor); and
In multicolor.xml write
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="#color/tabBgStart"
android:endColor="#color/tabBgEnd"
android:angle="270"/>
</shape>
Hope it will works definitely
To Change the text color you can use yourView.setTextColor(R.drawable.multicolor);
i hvn't used in with Canvas. see below code how i used it in textview.
public TextView getTextClipArt1(){
TextView textView = new TextView(context);
Typeface tf = new MyTypeface(context, 0).getTypeface();
Shader textShader=new LinearGradient(0, 0, 0, 30,
new int[]{Color.GREEN,Color.BLUE},
new float[]{0, 1}, TileMode.CLAMP);
textView.setTypeface(tf);
textView.getPaint().setShader(textShader);
textView.getPaint().setStyle(Paint.Style.STROKE);
textView.getPaint().setStrokeWidth(2);
textView.setText("ABC");
textView.setTextSize(30);
textView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
return textView;
}
you can now draw textview as bitmap on canvas, Although i think these methods are also exist in paint class.
Hope useful to you.

Categories

Resources