Android - Bitmap Height = Textview Text Height? - android

Adding an image in a text view works. Changing the image height and width to text view text height not works. (Original Image "red circle" is: 32px x 32px)
Output looks like this:
test img http://img850.imageshack.us/img850/9500/m1f.png
XML:
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp" />
Code:
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.textView);
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
String getText = getResources().getString(R.string.getText);
textView.setText(getText);
SpannableStringBuilder ssb = new SpannableStringBuilder(getText);
Bitmap redcircle= BitmapFactory.decodeResource( getResources(), R.drawable.redcircle );
Bitmap resizedbitmap = Bitmap.createScaledBitmap(redcircle, (int)textView.getMeasuredHeight(), (int)textView.getMeasuredHeight(), true);
ssb.setSpan( new ImageSpan( resizedbitmap ), 3, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE );
textView.setText( ssb, BufferType.SPANNABLE );
}
EDIT:
I want, that the image height and width is equal text view text height. For example like this:
test img 2 http://img849.imageshack.us/img849/3163/r9x.png

Try using
ImageSpan(resizedbitmap, ImageSpan.ALIGN_BASELINE)
instead of
ImageSpan(resizedbitmap)
The default alignment of an ImageSpan is ALIGN_BOTTOM.

Related

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

How to find the Text Area(Height/Width) of TextView programmatically in android

I have an EditText, a Button and a TextView. On clicking the button, textview shows the text written in edittext. Is it possible to find the size of textview occupied depending upon text. i.e. If It has three characters "abc", what is width now, if it has 5 characters like "abcde" , then what is the width ?
Rect bounds = new Rect();
Paint textPaint = textView.getPaint();
textPaint.getTextBounds(text,0,text.length(),bounds);
int height = bounds.height();
int width = bounds.width();
or
textView.setText("bla");
textView.measure(0, 0);
textView.getMeasuredWidth();
textView.getMeasuredHeight();
Please try this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView edit = (TextView) findViewById(R.id.edit);
edit.setTextSize(20);
edit.setText("Hello, world");
edit.measure(0, 0);
int width = edit.getMeasuredWidth();
Log.w("width", width.toString());
}
Before you get width, you have to measure the view / label / text edit.
Please let me know if this is not working.
TextView txt = new TextView(mContext);
txt.setText("Some Text)";
int height = txt.getLineCount() * txt.getLineHeight();
int width = txt.getWidth();
Try this way,hope this will help you to solve your problem.
yourTextView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
int width = yourTextView.getMeasuredWidth();
int height = yourTextView.getMeasuredHeight();
}
});
please tell me width in??? do you want ?
TextView method getWidth() gives you width of your view, in pixels
TextView textView = (TextView)findViewById(R.id.textview);
textView.getWidth(); //width of your view, in pixels

TextView with too long Strings

I have this layout
<ScrollView>
<TextView android:id="#+id/textView" />
</ScrollView>
When I try to set a too long text, this Textview doesn't show that.
//OnCreate
//...
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText("..."); //Here is a text with more than 2500
//chars and at least have 10 \n char
//(it means has at least 10 paragraph)
How can do I show that text?
Edit One :
Even I set a background to that TextView and the TextView does'nt show that background
you can set
android:maxLines="1"
android:ellipsize="end"
to your textview, so the text which long than your textview will be hide.
Because android:singleLine="true" attribute has been deprecated, set the following attributes to your TextView:
android:ellipsize="end"
android:maxLines="1"
The TextView will then show only the text that can fit to your TextView, followed by an ellipsis ...
i dont know if this will help you but saw this on developer.android...
With Android 8.0 (API level 26) and higher, you can instruct a TextView to let the text size expand or contract automatically to fill its layout based on the TextView's characteristics and boundaries. This setting makes it easier to optimize the text size on different screens with dynamic content.
android:autoSizeTextType="uniform"
There are three ways you can set up the autosizing of TextView:
Default
Granularity
Preset Sizes
=================================================
readMore
Use this :
EditText thumbnailView = (EditText) findViewById(R.id.enterBearingNo_editText_id);
TextView messageView = (TextView) findViewById(R.id.string2);
String text = "LargeText";
Display display = getWindowManager().getDefaultDisplay();
FlowTextHelper.tryFlowText(text, thumbnailView, messageView, display);
FlowTextHelper.class
class FlowTextHelper {
static boolean mNewClassAvailable;
static {
if (Integer.valueOf(Build.VERSION.SDK) >= 8) { // Froyo 2.2, API level 8
mNewClassAvailable = true;
}
// Also you can use this trick if you don't know the exact version:
/*
* try {
* Class.forName("android.text.style.LeadingMarginSpan$LeadingMarginSpan2"
* ); mNewClassAvailable = true; } catch (Exception ex) {
* mNewClassAvailable = false; }
*/
}
public static void tryFlowText(String text, View thumbnailView,
TextView messageView, Display display) {
// There is nothing I can do for older versions, so just return
if (!mNewClassAvailable)
return;
// Get height and width of the image and height of the text line
thumbnailView.measure(display.getWidth(), display.getHeight());
int height = thumbnailView.getMeasuredHeight();
int width = thumbnailView.getMeasuredWidth();
float textLineHeight = messageView.getPaint().getTextSize();
// Set the span according to the number of lines and width of the image
int lines = (int) Math.round(height / textLineHeight);
// For an html text you can use this line: SpannableStringBuilder ss =
// (SpannableStringBuilder)Html.fromHtml(text);
SpannableString ss = new SpannableString(text);
ss.setSpan(new MyLeadingMarginSpan2(lines, width), 0, ss.length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
messageView.setText(ss);
// Align the text with the image by removing the rule that the text is
// to the right of the image
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) messageView
.getLayoutParams();
int[] rules = params.getRules();
rules[RelativeLayout.RIGHT_OF] = 0;
}
public static void tryFlowTextPrice(String text, TextView messageView,
Display display) {
// There is nothing I can do for older versions, so just return
if (!mNewClassAvailable)
return;
// Get height and width of the image and height of the text line
// thumbnailView.measure(display.getWidth(), display.getHeight());
// int height = thumbnailView.getMeasuredHeight();
// int width = thumbnailView.getMeasuredWidth();
float textLineHeight = messageView.getPaint().getTextSize();
// Set the span according to the number of lines and width of the image
// int lines = (int) Math.round(height / textLineHeight);
// For an html text you can use this line: SpannableStringBuilder ss =
// (SpannableStringBuilder)Html.fromHtml(text);
SpannableString ss = new SpannableString(text);
// ss.setSpan(new MyLeadingMarginSpan2(lines, width), 0, ss.length(),
// Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
messageView.setText(ss);
// Align the text with the image by removing the rule that the text is
// to the right of the image
// LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)
// messageView
// .getLayoutParams();
// int[] rules = params.getRules();
// rules[RelativeLayout.RIGHT_OF] = 0;
}
}

Underline a dynamically generated TextView in 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" />

Textview image in android

In my application i have to show an image in my text view. Also When i click 1st time 1 image should draw and clicking next time another image should be drawn.Is it possible to draw an image in textview?Please help me..
You can use
setCompoundDrawables(Drawable left, Drawable top, Drawable right, Drawable bottom)
for the textView
You can set a background image using the android:background attribute
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/image" />
Or programatically with the setBackgroundDrawable()or setBackgroundResource() methods:
textView.setBackgroundResource(R.drawable.image);
You can take an array of Drawables, an an index for that:
TextView tv;
Drawable[] drbl = new Drawable[4];
int drblIndex = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
drbl[0] = getResources().getDrawable(R.drawable.ic_launcher);
drbl[1] = getResources().getDrawable(R.drawable.img2);
drbl[2] = getResources().getDrawable(R.drawable.img3);
drbl[3] = getResources().getDrawable(R.drawable.right_arrow);
tv = (TextView) findViewById(R.id.textView1);
tv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
tv.setBackgroundDrawable(drbl[drblIndex++]);
if(drblIndex == drbl.length)
drblIndex = 0;
}
});
}
Then you can set values of that array as I have done.
Then onClick you can move to next Index and can set new Drawable-Image to TextView.
When Index reaches to last value, set it to zero, simply.
Set OnClickListener on the TextView and in its onClick() method, use the following methods to set the images :
textview.setBackgroundDrawable();
or
textview.setBackgroundResource();
try this code, textview with image.
CharSequence dogstate = null ;
Html.fromHtml("" + " "
+ "your text" + "", featuregetter, null);
dogatstatus.append(dogstate);
private ImageGetter featuregetter = new ImageGetter() {
public Drawable getDrawable(String source) {
Log.i(" get drawable mathod ", "");
Bitmap B = BitmapFactory.decodeResource(getResources(),
R.drawable.bone);
BitmapDrawable BD = new BitmapDrawable(B);
BD.setBounds(0, 0, B.getWidth(), B.getHeight());
return BD;
}
};

Categories

Resources