Making objects in Android from regex - java

I am writing an Android application which gets string to parse using regex. Let's say it gets
'Tis an example image of a beaver {[beaver.jpg]} having an afternoon tea.
And what I want to get is TextView with 'Tis an example image of a beaver, ImageView beaver.jpg and an another TextView having an afternoon tea..
How (if possible) is creating objects possible after reading such string and parsing with regex?

Your custom view class should have a constructor that takes three String parameters, one for the path of the image, one for text to be displayed before the image and one for the text to display afterwards.
class YourView {
public YourView(String imgPath, String beforeImg, String afterImg){
//add TextView for text before image
//add ImageView for image
//add TextView for text after image
}
}
If your image will always be enclosed in a {[ ]}, the regex (.+)\\{\\[(.+)\\]\\}(.+) will capture everything before the {[ in capturing group 0, everything between {[ and }] (i.e. the image path) in group 1, and everything after }] in group 2.
If you use a Java Matcher You can then achieve your desired result like:
String pre, path, post;
while (matcher.find()){
pre = matcher.group(0);
path = matcher.group(1);
post = matcher.group(2);
YourView view = new YourView(path, pre, post);
//add view
}
Note that, if the image is at the end or beginning of the text, you'll simply be passing empty strings as the third/first parameters here, which will result in the creation of empty TextViews, which should be harmless (or you can do a check and not create one for empty strings).
That said, also note that above code is untested (but should give you the general idea), and that I'm a Java programmer with little experience in Android - so let me know if there's an Android-specific reason this wouldn't work

Related

How to change the color of specific strings in TextView

I have a scrollable TextView that has texts like this
...
Tom: sometext
Jack: anothertext
Sam: something
...
So I get this data as a JSON object, then I seperate the keys and values, then adding to a string. Then I set the text of TextView as this final string.
What I want is, I would like to make different colors for Tom, Jack, Sam. I have found HTML library but all solutions changes the whole TextView. I want to change specific parts of the text and since I get a JSON data first and I'm adding this JSON values to a string part by part, I thought I can do something like this string += <HTML color change> JSON["key"] + JSON["anotherKey"].
Is it possible to change specific parts of the text of a TextView object?
Take a look at spannable Strings. You will probably end up with something like this.
val spannable = SpannableStringBuilder("Text " + JSON["key"])
spannable.setSpan(
ForegroundColorSpan(Color.RED),
5, // start
5 + JSON["key"].length, // end
Spannable.SPAN_EXCLUSIVE_INCLUSIVE
)
See https://developer.android.com/guide/topics/text/spans for more info regarding spans.
Note: this example is in Kotlin but it's pretty much the same in Java.
You can change text color in TextView using below code snippets.
val blackColor= ContextCompat.getColor(context, R.color.black)
val redColor= ContextCompat.getColor(context, R.color.red)
textView.text = HtmlCompat.fromHtml("<font color=\"$blackColor\">Welcome to </font> <font color=\"$redColor\">Stack Overflow </font>", HtmlCompat.FROM_HTML_MODE_LEGACY)
Above code is in kotlin , its same as Java you can convert to Java.
Hope it will work for you !

How do I get specific line text in a textview and use webview to load the text(url)

Recently I want to get specific line text in a textview and I want to use a webview to load the text,I ve found some code references which I think is useful but not work for me well.
Textview:
A
Http://ABC.com.jp
C
I want to load line 2 URL.
Sorry for my low responsibility, now I still updating and modifying my source code,I am new in java and this is not my main profit,besides I will keep learning.
Target =(TextView)findViewbyid(R.id.abc);
myTextView = (TextView)findViewbyid(R.id.id1);
int startL= myTextView.getLayout().getLineStart(2);
//^start line
int endL = myTextView.getLayout().getLineEnd(3);
//^end line
String getResults = myTextView.getText().substring(startL, endL);
Target.setText(getResults);
//benefits of using get line end & start is that it can select multiple line content from a large content,also it can be used in selecting single line or specific line.

Android - How to define sets of drawable images to be shown in edittext or text view

I'm trying to do the next thing - let's say i have a menu with 5 drawable images (could be more but that's not the point), now when a user press on one drawable then it will be shown next a text that is already shown in the edittext.
Also I would like to allow the user add as many drawables as he wants.
So what i do understand is the next code lines -
Using map and defines the pairs of keyword and matching drawable -
private HashMap<String, Integer> emoticons = new HashMap<String, Integer>();
emoticons.put("[-smile-]", R.drawable.smile);
emoticons.put("[-tongue-]", R.drawable.tongue);
emoticons.put("[-cool-]", R.drawable.cool);
emoticons.put("[-sad-]", R.drawable.sad);
emoticons.put("[-cry-]", R.drawable.cry);
fillArrayList();
private void fillArrayList() {
Iterator<Entry<String, Integer>> iterator = emoticons.entrySet().iterator();
while(iterator.hasNext()){
Entry<String, Integer> entry = iterator.next();
arrayListSmileys.add(entry.getKey());
}
}
First of all - I've decided to define the keywords like the next pattern - [-keyword-] - because I assume in that way it will be much more easy to get the keywords from the String.
Now, the thing that I'm getting stuck in, is how should I read the String, and how to change the keywords from the String into the drawable.
So let's say the user want to write the next line (using the drawables) -
I am [-smile-] everything [-cool-]
So what I try to do is, something that can read this string and when it getting into [-keyword-], then it knows to show it to the user as drawable from the map pairs.
Thanks for any kind of help
If I'm working out your problem correctly you want to use "smileys" in your text?
You can use HTML in TextViews and display the images with image tags.
yourTextView.setText(Html.fromHtml("I am <img src='img_smile'>smile</img> everything <img src='img_cool'>cool</img>"));

Android java : Dealing whith xml's parsed String

I have an xml which Text looks like this :
<LINE>here is some text, it is going,going, and then return is pressed
and the text is going from the next line</LINE>
now when I do :
XmlPullParcer xpp;
//then all the parcing, try/catch stuff, finding needed tag
String s=xpp.getText();
myTextView.setText(s);
(of course, I cut all the code, but you got the idea)
what I see on the screen is not one solid line with no formatting as I wish, but the same two-line text
So, what I see on the screen is :
here is some text, it is going,going, and then return is pressed
and the text is going from the next line
and I want :
here is some text, it is going,going, and then return is pressed and but text is going in one line
please tell me how can I process my String s so it can be shown in a TextView in one line
It looks like the line in XML itself is having a line feed or carriage return. So try to replace them with empty string via String replace method. You can refer to link below for more details:
http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#sum
Also make sure the TextView in layout has singleline attribute set to true and layout_width set to match_parent.

Prevent typing in the same style in JTextPane

forgive me for a possible misleading title, but the problem is a bit hard to describe.
I'm currently trying to create a basic texteditor using a JTextPane in Java and I've run into an issue.
As you know in most texteditors you can put your caret/cursor behind a piece of styled text (for example text which is bold) and then you can continue typing in that same style (Eg. append more bold characters).
Luckely this is present by default in the JTextPane, but I want to disable it for a certain style. Mainly the URL-style I coded (basicly this one just sets the HTML.Attribute.HREF attribute in the style to an URL).
So if I would put my caret behind a word (or piece of text) which is an URL, I want to ensure that the next characters which will be added, will not be in the URL-style.
Eg. I think tinymce has this behaviour:
You select text
Click on the Insert URL button
Insert the URL
Place the cursor right after the URL and start typing again in normal style
Is there a way to enforce this behaviour in a JTextPane?
I was thinking about something like this:
Adding a listener for content changes in the document
Check if the added characters were placed right behind a piece of text with the URLstyle
If that was the case => remove the "href" attribute from the style of those characters
The code i use for setting the URL-style to the selected text can be found below. "dot" and "mark" are retrieved from the caret.
SimpleAttributeSet attr = new SimpleAttributeSet(doc.getCharacterElement(dot).getAttributes());
StyleConstants.setUnderline(attr, true);
StyleConstants.setForeground(attr, Color.BLUE);
attr.addAttribute(HTML.Attribute.HREF, url);
doc.setCharacterAttributes((dot < mark) ? dot : mark, length, attr, true);
(Note: To be able to tell the difference between normal "blue underlined" text and an URL, the HREF attribute is used for an URL.)
PS: This is my first question here, so hopefully I gave enough information. ;)
Language: Java, JDK 1.7
Thanks in advance.
Add a CaretListener to detect move and check whether current caret position needs the style reset. If it's detected use
StyledEditorKit's method
public MutableAttributeSet getInputAttributes()
Here just remove the attributes you don't need (URL, blue, underline).
I thought I'd share my solution to the problem (found with the help of StanislavL's answer - thanks again for putting me on the right track).
The following method is called from within a caretlistener, passing the attributes found via the "getInputAttributes"-function and the dot and mark of the caret.
private void blockURLTyping(MutableAttributeSet inputAttr, int dot, int mark)
{
StyledDocument doc = getStyledDocument();
int begin = (dot < mark) ? dot - 1 : mark - 1;
if(begin >= 0)
{
Element dotEl = doc.getCharacterElement(begin);
Element markEl = doc.getCharacterElement((dot < mark) ? mark : dot);
AttributeSet dotAttr = dotEl.getAttributes();
AttributeSet markAttr = markEl.getAttributes();
if(dotAttr.isDefined(HTML.Attribute.HREF)) // Ensure atleast one of them isn't null
{
if(dotAttr.getAttribute(HTML.Attribute.HREF) == markAttr.getAttribute(HTML.Attribute.HREF))
{
inputAttr.addAttribute(HTML.Attribute.HREF, dotAttr.getAttribute(HTML.Attribute.HREF));
inputAttr.addAttribute(StyleConstants.Foreground, Color.BLUE);
inputAttr.addAttribute(StyleConstants.Underline, true);
return;
}
}
}
if(inputAttr.isDefined(HTML.Attribute.HREF)) // In all other cases => remove
{
inputAttr.removeAttribute(HTML.Attribute.HREF);
inputAttr.removeAttribute(StyleConstants.Foreground);
inputAttr.removeAttribute(StyleConstants.Underline);
}
}
Important note; The inputAttributes do not update when the caretposition changes but stays within the same element.
So: when the caret is positioned at the end of the URL, behind the last character => you remove the three attributes you can see in the code above => However when the caret is moved to another position within the URL, the attribute stays removed because the set does not update.
So in practice this means that when you remove attributes from the attributeset, they will stay removed untill the StyledEditorKit updates the inputattributes.
To work around this problem I decided to add the attributes again if the caret is in the middle of an URL, allowing you to insert characters in the middle of the URL - but not append or prepend characters (like I wanted).
The code can probably be optimized a bit more because in most cases dot==mark, but I wanted to share this solution.
PS: The comparison of the HREF-attributes is to deal with the situation where two different URLs are positioned next to eachother in a text. It basicly should check if they are both different instances of a certain object even if the URL itself might be the same.
Code that calls this function:
#Override
protected void fireCaretUpdate(CaretEvent e)
{
super.fireCaretUpdate(e);
MutableAttributeSet attr = getStyledEditorKit().getInputAttributes();
int dot = e.getDot();
int mark = e.getMark();
blockURLTyping(attr, dot, mark);
...
}

Categories