I want to calculate string font width in pixels in android. I am having string array and I am appending all these array elements to form one string. so I have to set fixed spacing in between two consecutive array element.i am placing this final string into textview. Finally I am adding this textview to tablerow. In short i want to view table structure with title and values. I have seen many post over here but not getting solution for this.
Thanks in advance...!!!
Looks like there is a measureText method available on Paint. I also found an example:
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setStrokeWidth(5);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setTextSize(64);
mPaint.setTypeface(Typeface.create(Typeface.SERIF, Typeface.ITALIC));
// ...
float w = mPaint.measureText(text, 0, text.length());
Thanks Jake for the working solution, yet I found this to work for me too:
someText = "Lorem Ipsum";
TextView myTextView = (TextView) findViewById(R.id.myTextView);
float w = myTextView.getPaint().measureText(someText);
Getting the Paint directly from the TextView that I'm going to work with makes me feel that the anwser will be more accurate.
I don't know if this works, but it can.
int textSize=20;
Paint p=new Paint();
p.setTextSize(textSize);
String string="Hello im a string.";
public int getStringWidt()
{
return string.length*textSize;
}
Related
This is what happened when I Used
I want to get compliment text color from palette object
I tried this, but it didn't work out as supposed to be
palette.getVibrantSwatch().getTitleTextColor();
Please help me in showing right Way of Obtaining text color Using Palette
It takes some time to generate colors from supplied resource, that is why you should use Pallet asynchronously.
Bitmap bm = BitmapFactory.decodeResource(getResources(), VersionData.getOsDrawable(osVersion));
Palette.PaletteAsyncListener listener = new Palette.PaletteAsyncListener() {
public void onGenerated(Palette palette) {
Log.d("Palette", "Palette has been generated");
TextView tv1 = (TextView) findViewById(R.id.tv1);
TextView tv2 = (TextView) findViewById(R.id.tv2);
// use initialized Pallet here tv1.setBackgroundColor(palette.getVibrantColor(0x000000));
tv2.setBackgroundColor(palette.getVibrantColor(0x000000));
//Noticed the Expanded white doesn't show everywhere, use Palette to fix this
collapsingToolbar.setExpandedTitleColor(palette.getVibrantColor(0x000000));
}
};
// Start this Async, because it takes some time to generate
Palette.from(bm).generate(listener);
There is a excellent Material Design sample project
https://github.com/mwolfson/android-historian
I am new to Android and I am trying to change the background of an ImageView in Java. This part is working. The problem is I have a 4 images and I would like to randomly choose one and display the image.
For example I have an array of drawables as such:
String[] images = new String[4];
images[0] = "R.drawable.i1";
images[1] = "R.drawable.i2";
images[2] = "R.drawable.i3";
images[3] = "R.drawable.i4";
I was trying to use this to choose a random one:
int idx = new Random().nextInt(images.length);
String random = (images[idx]);
However, I cannot seem to get the setBackground for the imageview to work with these.
For example, I tried:
images.setBackgroundDrawable( getResources().getDrawable(R.drawable.images[random]) );
I know I am not doing it correctly however that is what I would like to do.
You can try this:
int[] images = new int[4];
images[0] = R.drawable.i1;
images[1] = R.drawable.i2;
images[2] = R.drawable.i3;
images[3] = R.drawable.i4;
int idx = new Random().nextInt(images.length);
int random = (images[idx]);
images.setBackgroundDrawable( getResources().getDrawable(images[random]) );
Your problem seems to be, that you want to call a Method through a String. Thats absolutly nonesense unless you work with java SQL calls or XML...whatever. you need the actual image Object if you call your draw method.
well there is a simple solution :D
Instead of using an String[]. Use a ArrayList<Image>
after that you can call the method list.shuffle().
some pseudo Code:
ArrayList<Image> yourImages = new Arraylist<>();
yourImages[1] = image1
yourImages[2] = image2
...
yourImages.shuffle(); //shuffles your list
print(yourImages[1]);
print(yourImages[2]);
...
the first advatage is that your pictures will be displayed at random.
the second advantage is that there is no duplicate of each displayed picture.
PS: It would also work with an Image[] + the Random class. But how come, choose a String[]. a String is a representation of an Text... not an image.
I was wondering if what i want is even possible.
Trying some coding for Android but i have a little issue and i hope someone can help me with this.
I have
ImageView img1 = (ImageView) findViewById(R.id.circleselect1);
Now what is want is the Integer at the end of my resource id incremented with one
Like
ImageView img1 = (ImageView) findViewById(R.id.circleselect+integer);
I know this is not working but is there a way to accomplice what i want?
I saw your comment I have a counter, and i have 4 R.id.circleselect's like R.id.circleselect1, R.id.circleselect2, R.id.circleselect3. R.id.circleselect4 i want to get the right source if the counter hits the next intand the solution you are asking for is a bad idea.
Instead try this one out. Create an array of the ID's that you want and then use them as you want.
int[] array = new int[]{R.id.circleselect1,R.id.circleselect2,R.id.circleselect3,R.id.circleselect4};
IDs as they appear in the R class (more precisely, in the id class inside R) are just static fields.
You can access them dynamically by using
R.id.class.getDeclaredField("circleselect" + i).getInt(null);
where i is the integer at the end of the name.
This is not advised as this is very un-OOP and will break if the field does not exist.
Something Like this?
String circle = "circleselect" + integer; // or integer.toString()
int resID = getResources().getIdentifier(circle, "id", getPackageName());
ImageView img = (ImageView) findViewById(resID);
I want to color specific words in a string.
At the moment I am using this:
SpannableString txt = new SpannableString(txt.toString());
Pattern color = Pattern.compile("My Text");
Matcher mat = color.matcher(txt);
while(mat.find()) {
txtt.setSpan(new ForegroundColorSpan(Color.BLUE), mat.start(), mat.end(), 0);
}
This is working perfect for one text.. but the problem is that I want color more than one piece of text in differed colors.
I already tried it with:
line = line.replace("My Text",
"<font color='#0000ff'>" + "$0" + "</font>");
But StringBuilder seems not to work with this
textViewTs.setText(Html.fromHtml(line));
UPDATE:
if i try to continue the while loop like this
SpannableString txtt = new SpannableString(txt.toString());
Pattern color = Pattern.compile("first text");
Matcher mat = color.matcher(txt);
Pattern color2 = Pattern.compile("second text");
Matcher mat2 = color2.matcher(txt);
while(mat.find()) {
txtt.setSpan(new ForegroundColorSpan(Color.BLUE), mat.start(), mat.end(), 0);
} while(mat2.find()) {
txtt.setSpan(new ForegroundColorSpan(Color.YELLOW), mat.start(), mat.end(), 0);
}
textViewTs.setText(txtt);
I get a error that reads java.lang.IllegalStateException: No successful match so far
Any good way to solve this?
try with the replace() method from the SpannableStringBuilder (http://developer.android.com/reference/android/text/SpannableStringBuilder.html) instead of using the setSpan().
I have something perfect for you! I wrote some code and uploaded it to my website. You can find the page with intrsuctions on how to use it here and the code to add to your src folder here.
I made this for LibGDX but it should work the same. All you need to do is change the code to change the color of the text and the code to draw the text! For example, if your using SurfaceView you could replace this:
if(character == 'r'){
font.setColor(Color.RED);
}
with this:
if(character == 'r'){
paint.setColor(Color.RED);
}
Just an example, I don't thinks that's what your using, right? Just change it however you need it.
How it Works:
To change the color just add codes to the string you want to draw. For example, just say you want to draw "Hello World!" with "Hello" in red and "World" in blue at coordinates 50, 40 just run this:
ColorText.draw("&rHello &bWorld!", 1, batch, 50, 40);
Note! You will have to do a lot of finetuning for this to work for you but the basic code is there for handling the string.
I am trying to make an app that lets the user store and saves contacts. It can save, but it has problems listing.
I have a for loop that runs through the database and prints a set of data for each contact (each row), an image (actually its a string because it passes the path) and a string. It prints them in a scrollview with a linear layout for each contact (each contact has a linear layout of its own, so that i can let one contact occupy a row each). The images come out, however, the textviews are nowhere to be found.
Using log.d(textview.getText()); it confirms that the textviews are created and take up space.
http://chesnutcase.heliohost.org/derpbox/itv1.png
Two "contacts" with names, not printed out. The space inbetween is presumbly by the textview.
http://chesnutcase.heliohost.org/derpbox/itv2.png
Another two "contacts", but without names. The dont have a space between each other. Or at least, a significantly smaller space.
Code:
DatabaseHandler db = new DatabaseHandler(this);
int a = (int) (long) db.countRows();
LinearLayout theLayout = (LinearLayout)findViewById(R.id.contactsList);
for(int i = 0;i<a;i++){
ImageButton image = new ImageButton(this);
int density=getResources().getDisplayMetrics().densityDpi;
LinearLayout.LayoutParams vp = new LinearLayout.LayoutParams(density,density, 0.5f);
image.setLayoutParams(vp);
image.setScaleType(ImageView.ScaleType.FIT_END);
int b = a - i;
try {
image.setImageBitmap(decodeUri(Uri.parse(db.getContactData("photo_path")[i])));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
theLayout.addView(image);
TextView tv = new TextView(this);
tv.setText(db.getContactData("name")[i]);
Log.d("UserLog","name is " + db.getContactData("name")[i]);
Log.d("UserLog","textfield contains " + tv.getText());
LinearLayout.LayoutParams vp2 = new LinearLayout.LayoutParams(0,0,1f);
tv.setLayoutParams(vp2);
tv.setBackgroundColor(Color.RED);
theLayout.addView(tv);
}
Any solutions? Thanks in advance
Double check which orientation you've applied to the LinearLayout of your contacts list.
You are setting bad LayoutParams to your TextView. You're making your TextView 0px by 0px with a weight of 1.
LinearLayout.LayoutParams vp2 = new LinearLayout.LayoutParams(0,0,1f);
tv.setLayoutParams(vp2);
Try using one of the MATCH_PARENT or WRAP_CONTENT constants. They're listed here: http://developer.android.com/reference/android/view/ViewGroup.LayoutParams.html#MATCH_PARENT
If you want your TextView to take up the remaining width of the screen I would leave the weight as 1, the width as 0, but you need to set the height to a constant like WRAP_CONTENT.
You're also setting the size of your ImageView to the device screen density (which is a constant) instead of setting a scaling size based off your screen density.
You probably need to call requestLayout(); in order to update the current view layout.
theLayout.requestLayout();
Also it seems you are creating a view with 0 width and 0 height with that layout params:
LinearLayout.LayoutParams vp2 = new LinearLayout.LayoutParams(0,0,1f);
It is better to use ListView for such list.
You will need to write only one Adapter, that's represent logic for creating one row on list.
I would recommend using a CursorAdapter and a layout xml file, this way you can design it to look exactly how you want, and preview it. It is a lot easier than setting all those fiddly LayoutParams
If you have to create them dynamically you may find the text colour is the same as the background, try setting it to something visible like bright red for testing. If you still don't see the text it may be that it's visibility isn't set to View.VISIBLE finally the layout may not be the correct size, a handy tip for this is set the background to a suitably eye catching colour, even if there is no text you should see a shaded block.