The keyboard changes its state after a space - android

I had a problem when I type the text I do not want the keyboard changes automatically, but after a space keyboard changes to the original state.
For example, I want to dial numbers that I move into this state the keyboard: But when I need to enter the number followed by a space, the keyboard itself is changed automatically:And it is necessary that the user himself can change the state of the keyboard, if it is necessary to enter characters. I use a mask on the text of Edit Text. With the help of this library set mask: MaskFormatter. an example of a mask: private static final String MASK = "99 AA 999999";
private EditText mInputCertificate;
#Override
public void setViews(View rootView, Bundle savedInstanceState) {
// Some code
mInputCertificate = (EditText) rootView.findViewById(R.id.input_car_certificate);
MaskFormatter maskFormatter = new MaskFormatter(MASK, mInputCertificate);
mInputCertificate.addTextChangedListener(maskFormatter);
}
There are ways to solve this problem?

I made my custom TextWatcher for EditText:
private String getString (String s) {
String newValue = s.replaceAll("\\s", "");
/*if (newValue.length() < 2 || newValue.length() >= 4) {
mEditText.setInputType(InputType.TYPE_CLASS_NUMBER);
} else {
mEditText.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
}*/
StringBuilder builder = new StringBuilder();
for (int i =0; i < newValue.length(); i++) {
if (i == 2 || i == 4) {
builder.append(' ');
builder.append(newValue.charAt(i));
} else {
builder.append(newValue.charAt(i));
}
}
return builder.toString();
}
#Override
public void afterTextChanged(Editable s) {
Log.d("EDITTEXT", "getEditable " + s);
String text = getString(s.toString());
mEditText.removeTextChangedListener(this);
mEditText.getText().clear();
mEditText.append(text.toUpperCase());
mEditText.addTextChangedListener(this);
mEditText.setSelection(mEditText.length());
}
This work for me. And I used .append(SomeText) instead .setText(SomeText).

Related

After spliting String into ArryList<String> i cannot read the text from any cell

I am an android noobie. What I am trying to do is to make this String an ArrayList. This is done. When i Print it On (with tv.setText) , the result is what i need but in this if i have right below i cannot find the "1".
The result i want to have is to store the text between the noumbers inside another ArrayList but to go there i have to be able to read the strings from the ArrayList.
public class MainActivity extends AppCompatActivity {
String text = "1Hello12People22Paul22Jackie21Anna12Fofo2";
TextView tv;
List<String> chars = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.tv);
PrinThemNow();
}
public void PrinThemNow(){
chars = Arrays.asList(text.split(""));
tv.setText(toString().valueOf(chars));
for(int i=0;i<chars.size();i++){
if(toString().valueOf(chars.get(i)) == " 1"){
Toast.makeText(this,"I found One",Toast.LENGTH_LONG).show();
//This if is not working while the TV's text shows " 1"
}
}
}
}
First, just a tip, from string to char[] you can use
char[] chars = myString.toCharArray();
because it has no sense to save a char array as a string ArrayList
but now the problem. you have your string and you wanna print the text between the numbers.
It's not really clear what is your goal but lets try.
I will suppose you used the char[] because it's 10 times better and easier
case 1) you wanna print text betweens "1"s
//lets loop the chars
bool firstOneFound = false;
int firstOccurrence = -1;
int secondOccurrence = -1;
int i = 0;
for(char c : chars){
//is it equals to 1?
if(c.equals('1')){
//check if we are already after the first 1
if(firstOneFound){
//if yes, we found the final one
secondOccurrence = i;
break;
}
else{
//this is the first occurrence
firstOccurrence = i;
firstOneFound = true;
}
}
i++;
}
if(firstOccurrence != -1 && secondOccurrence != -1){
String myFinalString = myString.subString(firstOccurrence, secondOccurrence);
}
case 2) you wanna print all text except numbers (maybe with a space instead)
for(char c : chars){
//check if it's a number
if(c >= '0' && c <= '9'){
//replace the number with anything else
c = ' '; //if you wanna have it as a space
}
}
//print the final string
String myFinalString = new String(chars);
NOTE:
You can also use ArrayList of string, just replace ' with "
hope it helps

How to change First letter of each word to Uppercase in Textview xml

i need to change the text="font roboto regular" to Font Roboto Regular in xml itself, how to do?
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="18sp"
android:textColor="#android:color/black"
android:fontFamily="roboto-regular"
android:text="font roboto regular"
android:inputType="textCapWords"
android:capitalize="words"/>
If someone looking for kotlin way of doing this, then code becomes very simple and beautiful.
yourTextView.text = yourText.split(' ').joinToString(" ") { it.capitalize() }
You can use this code.
String str = "font roboto regular";
String[] strArray = str.split(" ");
StringBuilder builder = new StringBuilder();
for (String s : strArray) {
String cap = s.substring(0, 1).toUpperCase() + s.substring(1);
builder.append(cap + " ");
}
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(builder.toString());
Try this...
Method that convert first letter of each word in a string into an uppercase letter.
private String capitalize(String capString){
StringBuffer capBuffer = new StringBuffer();
Matcher capMatcher = Pattern.compile("([a-z])([a-z]*)", Pattern.CASE_INSENSITIVE).matcher(capString);
while (capMatcher.find()){
capMatcher.appendReplacement(capBuffer, capMatcher.group(1).toUpperCase() + capMatcher.group(2).toLowerCase());
}
return capMatcher.appendTail(capBuffer).toString();
}
Usage:
String chars = capitalize("hello dream world");
//textView.setText(chars);
System.out.println("Output: "+chars);
Result:
Output: Hello Dream World
KOTLIN
val strArrayOBJ = "Your String".split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
val builder = StringBuilder()
for (s in strArrayOBJ) {
val cap = s.substring(0, 1).toUpperCase() + s.substring(1)
builder.append("$cap ")
}
txt_OBJ.text=builder.toString()
Modification on the accepted answer to clean out any existing capital letters and prevent the trailing space that the accepted answer leaves behind.
public static String capitalize(#NonNull String input) {
String[] words = input.toLowerCase().split(" ");
StringBuilder builder = new StringBuilder();
for (int i = 0; i < words.length; i++) {
String word = words[i];
if (i > 0 && word.length() > 0) {
builder.append(" ");
}
String cap = word.substring(0, 1).toUpperCase() + word.substring(1);
builder.append(cap);
}
return builder.toString();
}
you can use this method to do it programmatically
public String wordFirstCap(String str)
{
String[] words = str.trim().split(" ");
StringBuilder ret = new StringBuilder();
for(int i = 0; i < words.length; i++)
{
if(words[i].trim().length() > 0)
{
Log.e("words[i].trim",""+words[i].trim().charAt(0));
ret.append(Character.toUpperCase(words[i].trim().charAt(0)));
ret.append(words[i].trim().substring(1));
if(i < words.length - 1) {
ret.append(' ');
}
}
}
return ret.toString();
}
refer this if you want to do it in xml.
You can use
private String capitalize(final String line) {
return Character.toUpperCase(line.charAt(0)) + line.substring(1);
}
refer this How to capitalize the first character of each word in a string
android:capitalize is deprecated.
Follow these steps: https://stackoverflow.com/a/31699306/4409113
Tap icon of ‘Settings’ on the Home screen of your Android Lollipop
Device
At the ‘Settings’ screen, scroll down to the PERSONAL section and
tap the ‘Language & input’ section.
At the ‘Language & input’ section, select your keyboard(which is
marked as current keyboard).
Now tap the ‘Preferences’.
Tap to check the ‘Auto – Capitalization’ to enable it.
And then it should work.
If it didn't, i'd rather to do that in Java.
https://stackoverflow.com/a/1149869/2725203
Have a look at ACL WordUtils.
WordUtils.capitalize("your string") == "Your String"
Another approach is to use StringTokenizer class. The below method works for any number of words in a sentence or in the EditText view. I used this to capitalize the full names field in an app.
public String capWordFirstLetter(String fullname)
{
String fname = "";
String s2;
StringTokenizer tokenizer = new StringTokenizer(fullname);
while (tokenizer.hasMoreTokens())
{
s2 = tokenizer.nextToken().toLowerCase();
if (fname.length() == 0)
fname += s2.substring(0, 1).toUpperCase() + s2.substring(1);
else
fname += " "+s2.substring(0, 1).toUpperCase() + s2.substring(1);
}
return fname;
}
in kotlin, string extension
fun String?.capitalizeText() = (this?.toLowerCase(Locale.getDefault())?.split(" ")?.joinToString(" ") { if (it.length <= 1) it else it.capitalize(Locale.getDefault()) }?.trimEnd())?.trim()
Kotlin extension function for capitalising each word
val String?.capitalizeEachWord
get() = (this?.lowercase(Locale.getDefault())?.split(" ")?.joinToString(" ") {
if (it.length <= 1) it else it.replaceFirstChar { firstChar ->
if (firstChar.isLowerCase()) firstChar.titlecase(
Locale.getDefault()
) else firstChar.toString()
}
}?.trimEnd())?.trim()
As the best way for achieving this used to be the capitalize() fun, but now it got depricated in kotlin. So we have an alternate for this. I've the use case where I'm getting a key from api that'll be customized at front end & will be shown apparently. The value is coming as "RECOMMENDED_OFFERS" which should be updated to be shown as "Recommended Offers".
I've created an extension function :
fun String.updateCapitalizedTextByRemovingUnderscore(specialChar: String): String
that takes a string which need to be replaced with white space (" ") & then customise the words as their 1st character would be in caps. So, the function body looks like :
fun String.updateCapitalizedTextByRemovingUnderscore(
specialChar: String = "") : String {
var tabName = this
// removing the special character coming in parameter & if
exist
if (spclChar.isNotEmpty() && this.contains(specialChar)) {
tabName = this.replace(spclChar, " ")
}
return tabName.lowercase().split(' ').joinToString(" ") {
it.replaceFirstChar { if (it.isLowerCase())
it.titlecase(Locale.getDefault()) else it.toString() } }
}
How to call the extension function :
textView.text =
"RECOMMENDED_OFFERS".updateCapitalizedTextByRemovingUnderscore("_")
OR
textView.text = <api_key>.updateCapitalizedTextByRemovingUnderscore("_")
The desired output will be :
Recommended Offers
Hope this will help.Happy coding :) Cheers!!
capitalize each word
public static String toTitleCase(String string) {
// Check if String is null
if (string == null) {
return null;
}
boolean whiteSpace = true;
StringBuilder builder = new StringBuilder(string); // String builder to store string
final int builderLength = builder.length();
// Loop through builder
for (int i = 0; i < builderLength; ++i) {
char c = builder.charAt(i); // Get character at builders position
if (whiteSpace) {
// Check if character is not white space
if (!Character.isWhitespace(c)) {
// Convert to title case and leave whitespace mode.
builder.setCharAt(i, Character.toTitleCase(c));
whiteSpace = false;
}
} else if (Character.isWhitespace(c)) {
whiteSpace = true; // Set character is white space
} else {
builder.setCharAt(i, Character.toLowerCase(c)); // Set character to lowercase
}
}
return builder.toString(); // Return builders text
}
use String to txt.setText(toTitleCase(stringVal))
don't use android:fontFamily to roboto-regular. hyphen not accept. please rename to roboto_regular.
To capitalize each word in a sentence use the below attribute in xml of that paticular textView.
android:inputType="textCapWords"

Pop up Arabic/Urdu custom keyboard on Edittext Issue

I am working on app where i use Urdu Custom Keyboard its work fine but the problem is that when i type any-word e.g. (سلام), cursor become not works at mid character for example cut/copy/paste or deleting (ا) character from the mid from word are not work.
i uses rough technique just appending characters but is also work fine.
For taping any alphabetic
private void addText(View v) {
// String b = "";
// b = (String) v.getTag();
// urdu_word.setText(b);
if (isEdit == true) {
String b = "";
b = (String) v.getTag();
if (b != null) {
Log.i("buttonsOnclick", b);
// adding text in Edittext
mEt.append(b);
}
}
}
For back button tapping
private void isBack(View v) {
if (isEdit == true) {
CharSequence cc = mEt.getText();
if (cc != null && cc.length() > 0) {
{
mEt.setText("");
mEt.append(cc.subSequence(0, cc.length() - 1));
}
}
}
}
Here the screenshot clear my problem to you people
I used a lot of library and code from github but don't catch good idea
1) Keyboard-1
2) Keyboard-2
3) Keyboard-3
4) Keyboard-4
i checked all these keyboard and more from libs, have same cursor issue, how to manage fully my custom keyboard by deleting character from mid and copy my written text copy paste like normal keyboard with EditText, thanks in advance all of you :)
Thanks God i solved my issue using simple logic.
For back button
private void isBack(View v) {
// char[] tempChar = null;
if ((mEt.getText().toString().length() > 0)) {
int temp = mEt.getSelectionEnd() - 1;
if (temp >= 0) {
mEt.setText((mEt.getText().toString()
.substring(0, mEt.getSelectionEnd() - 1).concat(mEt
.getText()
.toString()
.substring(mEt.getSelectionEnd(),
mEt.getText().length()))));
mEt.setSelection(temp);
}
}
}
For adding any character
private void addText(View v) {
int temp = mEt.getSelectionEnd();
if (temp >= 0) {
String b = "";
b = (String) v.getTag();
mEt.setText((mEt.getText().toString()
.substring(0, mEt.getSelectionEnd()) + b.concat(mEt
.getText().toString()
.substring(mEt.getSelectionEnd(), mEt.getText().length()))));
mEt.setSelection(temp + 1);
}
}
for copy paste i added few lines code to EditText
<EditText
android:id="#+id/xEt"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="#drawable/edittextshape"
android:ems="10"
android:focusable="true"
android:focusableInTouchMode="true"
android:gravity="top"
android:imeOptions="actionDone"
android:padding="15dp"
android:singleLine="false"
android:visibility="visible" />

How to use replaceAll() correct

I have a hangman-app which I fetch a random word from Db i created, then I save it to randomedWord and then i make another String for holding randomedWord but replaced with only "_". This hiddenWord is displayed so the user knows how many chars there is.
When a user hits Enter a onlicklistener fires guess() method:
I have following code which initates a local String which has the value of a TextView(userInput). Then if randomedWord contains the guess I want to put in guess into the same position as it is in the randomedWord, but now to hiddenWord and then update the TextView again.
Guess method:
public void guess()
{
String guess = userInput.getText().toString();
if(randomedWord.contains(guess))
{
hiddenWord = hiddenWord.replaceAll(guess, guess);
this.wordHolder.setText(hiddenWord);
} else
{
showImages();
}
}
The problem I think is this line:
hiddenWord = hiddenWord.replaceAll(guess, guess);
because hiddenWord just contains "_" and therefore I can't replace with (guess, guess) where the first is WHAT to be replaced and last is WITHWHAT.
How do I replace the same POSITION as it is in randomedWord with guess into hiddenWord?
I would change your approach slightly. When a user inputs and guess() is called, find all occurences of that guess in randomedWord and then set the characters in hiddenWord to guess. Using StringBuilder and String.indexOf(), it would look something like this. Also, guess will need to be a char:
StringBuilder builder = new StringBuilder(hiddenWord);
int index = word.indexOf(guess);
while (index >= 0) {
builder.setCharAt(index, guess);
index = word.indexOf(guess, index + 1);
}
hiddenWord = builder.toString();
My solution to the problem looks like this:
// INVWORD METHOD WHICH TURNS THE FETCHED WORD INTO A COPY BUT ONLY "_"
public void invWord()
{
hiddenWord = randomedWord;
hiddenWord = hiddenWord.replaceAll(".", "_");
}
// GUESS METHOD WHICH IS CALLED WHEN ENTER-BUTTON ISCLICKED
public void guess() throws IndexOutOfBoundsException
{
char guess = userInput.getText().charAt(0);
StringBuilder builder = new StringBuilder(hiddenWord);
String j = ""+guess;
int index = randomedWord.indexOf(guess);
if (randomedWord.contains(j))
{
while (index >= 0)
{
builder.setCharAt(index, guess);
index = randomedWord.indexOf(guess, index + 1);
hiddenWord = builder.toString().trim();
wordHolder.setText(hiddenWord);
if (hiddenWord.trim().contains(randomedWord))
{
winner();
}
}
}
else
{
showImages();
}
}
Problem is that I would need to add a +" " to the hiddenWord = hiddenWord.replaceAll(".", "_"); to make the word be like _ _ _ _ _ and makes the user see how many ketters the word is. In my solution it will only be long ____, but it works. If I set index*2 at builder.setCharAt(index, guess); the formatting will be good but then winner(); is never run, I guess because the " " makes the hiddenWord no longer = ranomedWord.
How can I solve this?
Got it all solved! The feeling when everything works smoothly.... :)
Heres the code:
// Set listener to enter-button and do guess when textfield is not empty and toast that input need if it is
enterLetterButton.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
if (!(userInput.getText().toString().isEmpty()) )
{
guess();
} else if (userInput.getText().toString().isEmpty())
{
Toast toast = Toast.makeText(getApplicationContext(), "You need to insert a letter", Toast.LENGTH_SHORT);
toast.show();
}
}
});
// invWord() method. Converts the randomedWord to a string of "_".
public void invWord()
{
hiddenWord = randomedWord;
hiddenWord = hiddenWord.replaceAll(".", "_" +" ");
}
//guess() method. Puts the guess(char) at the index fetched and if the hiddenWord contains no more "_" winner() is called
public void guess() throws IndexOutOfBoundsException
{
char guess = userInput.getText().charAt(0);
StringBuilder builder = new StringBuilder(hiddenWord);
String j = ""+guess;
int index = randomedWord.indexOf(guess);
if (randomedWord.contains(j))
{
while (index >= 0)
{
builder.setCharAt(index*2, guess);
index = randomedWord.indexOf(guess, index + 1);
hiddenWord = builder.toString().trim();
wordHolder.setText(hiddenWord);
if (!(hiddenWord.toString().contains("_".toString())) )
{
winner();
}
}
}
else
{
showImages();
}
}

Html List tag not working in android textview. What can I do?

Html List tag not working in android TextView. This is my string content:
String str="A dressy take on classic gingham in a soft, textured weave of stripes that resembles twill. Take a closer look at this one.<ul><li>Trim, tailored fit for a bespoke feel</li><li>Medium spread collar, one-button mitered barrel cuffs</li><li>Applied placket with genuine mother-of-pearl buttons</li><li>;Split back yoke, rear side pleats</li><li>Made in the U.S.A. of 100% imported cotton.</li></ul>";
I loaded it in a text view like this:
textview.setText(Html.fromHtml(str));
The output looks like a paragraph. What can I do? Is there any solution for it?
Edit:
webview.loadData(str,"text/html","utf-8");
As you can see in the Html class source code, Html.fromHtml(String) does not support all HTML tags. In this very case, <ul> and <li> are not supported.
From the source code I have built a list of allowed HTML tags:
br
p
div
em
b
strong
cite
dfn
i
big
small
font
blockquote
tt
monospace
a
u
sup
sub
So you better use WebView and its loadDataWithBaseURL method. Try something like this:
String str="<html><body>A dressy take on classic gingham in a soft, textured weave of stripes that resembles twill. Take a closer look at this one.<ul><li>Trim, tailored fit for a bespoke feel</li><li>Medium spread collar, one-button mitered barrel cuffs</li><li>Applied placket with genuine mother-of-pearl buttons</li><li>;Split back yoke, rear side pleats</li><li>Made in the U.S.A. of 100% imported cotton.</li></ul></body></html>";
webView.loadDataWithBaseURL(null, str, "text/html", "utf-8", null);
I was having the same problem, and what I did is overriding the default TagHandler. This one worked for me.
public class MyTagHandler implements TagHandler {
boolean first = true;
String parent = null;
int index = 1;
#Override
public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
if (tag.equals("ul")) {
parent = "ul";
} else if (tag.equals("ol")) {
parent = "ol";
}
if (tag.equals("li")) {
if (parent.equals("ul")) {
if (first) {
output.append("\n\t•");
first = false;
} else {
first = true;
}
} else{
if (first) {
output.append("\n\t"+index+". ");
first = false;
index++;
} else {
first = true;
}
}
}
}
}
and for displaying the text...
myTextView.setText(Html.fromHtml("<ul><li>I am an Android developer</li><li>Another Item</li></ul>", null, new MyTagHandler()));
[Edit]
Kuitsi has also posted an really good library that does the same, got it from this SO link.
Full sample project is located at https://bitbucket.org/Kuitsi/android-textview-html-list.
Sample picture is available at https://kuitsi.bitbucket.io/stackoverflow3150400_screen.png
This solution is closest to masha's answer. Some code is also taken from inner class android.text.Html.HtmlToSpannedConverter. It supports nested ordered and unordered lists but too long texts in ordered lists are still aligned with item number rather than text. Mixed lists (ol and ul) needs some work too. Sample project contains implementation of Html.TagHandler which is passed to Html.fromHtml(String, ImageGetter, TagHandler).
Edit: For wider HTML tag support, https://github.com/NightWhistler/HtmlSpanner might also be worth trying.
A small fix to Aman Guatam code. The function above has problem of rendering newline character. For example: if before <li> tag is a <p> tag, 2 newline characters are rendered. Here is upgraded code:
import org.xml.sax.XMLReader;
import android.text.Editable;
import android.text.Html.TagHandler;
public class ListTagHandler implements TagHandler {
boolean first = true;
#Override
public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
// TODO Auto-generated method stub
if (tag.equals("li")) {
char lastChar = 0;
if (output.length() > 0)
lastChar = output.charAt(output.length() - 1);
if (first) {
if (lastChar == '\n')
output.append("\t• ");
else
output.append("\n\t• ");
first = false;
} else {
first = true;
}
}
}
}
WARNING
As of Android 7 android.text.Html actually supports li and ul tags and uses a basic BulletSpan(), which means in the latest versions of Android the Html.TagHandlersolutions posted here will be ignored
Make sure your code handles this change. In case you want a BulletSpan with a larger gap than the default, you can can replace it with another span:
val html = SpannableStringBuilder(HtmlCompat.fromHtml(source, HtmlCompat.FROM_HTML_MODE_COMPACT))
val bulletSpans = html.getSpans<BulletSpan>(0, html.length)
bulletSpans.forEach {
val spanStart = html.getSpanStart(it)
val spanEnd = html.getSpanEnd(it)
html.removeSpan(it)
val bulletSpan = BulletSpan(gapWidthInDp, context.getColor(R.color.textColorBlack))
html.setSpan(bulletSpan, spanStart, spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
Different solution using LeadingMarginSpan. Handles ordered and unordered lists as well as nesting.
public class ListTagHandler implements TagHandler
{
private int m_index = 0;
private List< String > m_parents = new ArrayList< String >( );
#Override
public void handleTag( final boolean opening, final String tag, Editable output, final XMLReader xmlReader )
{
if( tag.equals( "ul" ) || tag.equals( "ol" ) || tag.equals( "dd" ) )
{
if( opening )
{
m_parents.add( tag );
}
else m_parents.remove( tag );
m_index = 0;
}
else if( tag.equals( "li" ) && !opening ) handleListTag( output );
}
private void handleListTag( Editable output )
{
if( m_parents.get(m_parents.size()-1 ).equals( "ul" ) )
{
output.append( "\n" );
String[ ] split = output.toString( ).split( "\n" );
int lastIndex = split.length - 1;
int start = output.length( ) - split[ lastIndex ].length( ) - 1;
output.setSpan( new BulletSpan( 15 * m_parents.size( ) ), start, output.length( ), 0 );
}
else if( m_parents.get(m_parents.size()-1).equals( "ol" ) )
{
m_index++ ;
output.append( "\n" );
String[ ] split = output.toString( ).split( "\n" );
int lastIndex = split.length - 1;
int start = output.length( ) - split[ lastIndex ].length( ) - 1;
output.insert( start, m_index + ". " );
output.setSpan( new LeadingMarginSpan.Standard( 15 * m_parents.size( ) ), start, output.length( ), 0 );
}
}
}
If you only need to format a list, keep it simple and copy/paste a unicode character in your TextView to achieve the same result.
• Unicode Character 'BULLET' (U+2022)
I came here looking for TagHandler implementations. Both Truong Nguyen and Aman Guatam answers are very nice, but I needed a mixed version of both: I needed my solution not to overformat it and to be able to ressolve <ol> tags, since I'm parsing something like <h3>title</h3><ol><li>item</li><li>item</li><li>item</li></ol>.
Here's my solution.
import org.xml.sax.XMLReader;
import android.text.Editable;
import android.text.Html.TagHandler;
public class MyTagHandler implements TagHandler {
boolean first = true;
String parent = null;
int index = 1;
public void handleTag(final boolean opening, final String tag,
final Editable output, final XMLReader xmlReader) {
if (tag.equals("ul")) {
parent = "ul";
index = 1;
} else if (tag.equals("ol")) {
parent = "ol";
index = 1;
}
if (tag.equals("li")) {
char lastChar = 0;
if (output.length() > 0) {
lastChar = output.charAt(output.length() - 1);
}
if (parent.equals("ul")) {
if (first) {
if (lastChar == '\n') {
output.append("\t• ");
} else {
output.append("\n\t• ");
}
first = false;
} else {
first = true;
}
} else {
if (first) {
if (lastChar == '\n') {
output.append("\t" + index + ". ");
} else {
output.append("\n\t" + index + ". ");
}
first = false;
index++;
} else {
first = true;
}
}
}
}
}
Note that, since we are resetting the index value whenever a new list starts, it WILL NOT work if you nest lists like in <ol><li>1<ol><li>1.1</li><li>1.2</li></ol><li>2</li></ol>11.11.22
With that code, you would get 1, 1, 2, 3 instead of 1, 1, 2, 2.
You can simply replace the "li" with unicodes
#Override
public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
if (tag.equalsIgnoreCase("li")) {
if (opening) {
output.append("\u2022 ");
} else {
output.append("\n");
}
}
}
Sure, there ise a way of showing bullets in Android TextView. You can replace <li> tags with • (which is HTML code for bullet).
If you want to try other list icons, use the preferred one from the table is this link;
http://www.ascii-code.com/
You can use Html.TagHandler. Below can be used for kotlin
class UlTagHandler : Html.TagHandler {
override fun handleTag(
opening: Boolean, tag: String, output: Editable,
xmlReader: XMLReader
) {
if (tag == "ul" && !opening) output.append("\n")
if (tag == "li" && opening) output.append("\n\t•")
}
}
and
textView.setText(Html.fromHtml(myHtmlText, null, UlTagHandler()));
Lord Voldermort's answer is a good starting point. However I required ol tag to display ordered list 1. 2. 3. .... instead of bullets. Also, nested tags need special handling to work properly.
In my code, I have maintained stack(parentList) to keep track of opened and closed ul and ol tags and also to know the current open tag.
Also, a levelWiseCounter is used to maintain different counts in case of nested ol tags.
myTextView.setText(Html.fromHtml("your string", null, new CustomTagHandler()));
.
.
.
private static class CustomTagHandler implements TagHandler
{
int level = 0;
private LinkedList<Tag> parentList = new LinkedList<DetailFragment.CustomTagHandler.Tag>();
private HashMap<Integer, Integer> levelWiseCounter = new HashMap<Integer, Integer>();
#Override
public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader)
{
if (tag.equalsIgnoreCase("ul") || tag.equalsIgnoreCase("ol"))
{
if (opening)
{
if (tag.equalsIgnoreCase("ul"))
{
parentList.push(Tag.UL);
}
else
{
parentList.push(Tag.OL);
}
level++;
}
else
{
if (!parentList.isEmpty())
{
parentList.pop();
//remove counter at that level, in any present.
levelWiseCounter.remove(level);
}
level--;
if (level < 0)
{
level = 0;
}
}
}
else if (tag.equalsIgnoreCase("li"))
{
if (opening && level > 0)
{
//new line check
int length = output.toString().length();
if (length > 0 && (output.toString().charAt(length - 1) == '\n'))
{
}
else
{
output.append("\n");
}
//add tabs as per current level of li
for (int i = 0; i < level; i++)
{
output.append("\t");
}
// append dot or numbers based on parent tag
if (Tag.UL == parentList.peek())
{
output.append("•");
}
else
{
//parent is OL. Check current level and retreive counter from levelWiseCounter
int counter = 1;
if (levelWiseCounter.get(level) == null)
{
levelWiseCounter.put(level, 1);
}
else
{
counter = levelWiseCounter.get(level) + 1;
levelWiseCounter.put(level, counter);
}
output.append(padInt(counter) + ".");
}
//trailing tab
output.append("\t");
}
}
}
/**
* Add padding so that all numbers are aligned properly. Currently supports padding from 1-99.
*
* #param num
* #return
*/
private static String padInt(int num)
{
if (num < 10)
{
return " " + num;
}
return "" + num;
}
private enum Tag
{
UL, OL
}
}
How about the next code (based on this link) :
public class TextViewHtmlTagHandler implements TagHandler
{
/**
* Keeps track of lists (ol, ul). On bottom of Stack is the outermost list
* and on top of Stack is the most nested list
*/
Stack<String> lists =new Stack<String>();
/**
* Tracks indexes of ordered lists so that after a nested list ends
* we can continue with correct index of outer list
*/
Stack<Integer> olNextIndex =new Stack<Integer>();
/**
* List indentation in pixels. Nested lists use multiple of this.
*/
private static final int indent =10;
private static final int listItemIndent =indent*2;
private static final BulletSpan bullet =new BulletSpan(indent);
#Override
public void handleTag(final boolean opening,final String tag,final Editable output,final XMLReader xmlReader)
{
if(tag.equalsIgnoreCase("ul"))
{
if(opening)
lists.push(tag);
else lists.pop();
}
else if(tag.equalsIgnoreCase("ol"))
{
if(opening)
{
lists.push(tag);
olNextIndex.push(Integer.valueOf(1)).toString();// TODO: add support for lists starting other index than 1
}
else
{
lists.pop();
olNextIndex.pop().toString();
}
}
else if(tag.equalsIgnoreCase("li"))
{
if(opening)
{
if(output.length()>0&&output.charAt(output.length()-1)!='\n')
output.append("\n");
final String parentList=lists.peek();
if(parentList.equalsIgnoreCase("ol"))
{
start(output,new Ol());
output.append(olNextIndex.peek().toString()+". ");
olNextIndex.push(Integer.valueOf(olNextIndex.pop().intValue()+1));
}
else if(parentList.equalsIgnoreCase("ul"))
start(output,new Ul());
}
else if(lists.peek().equalsIgnoreCase("ul"))
{
if(output.charAt(output.length()-1)!='\n')
output.append("\n");
// Nested BulletSpans increases distance between bullet and text, so we must prevent it.
int bulletMargin=indent;
if(lists.size()>1)
{
bulletMargin=indent-bullet.getLeadingMargin(true);
if(lists.size()>2)
// This get's more complicated when we add a LeadingMarginSpan into the same line:
// we have also counter it's effect to BulletSpan
bulletMargin-=(lists.size()-2)*listItemIndent;
}
final BulletSpan newBullet=new BulletSpan(bulletMargin);
end(output,Ul.class,new LeadingMarginSpan.Standard(listItemIndent*(lists.size()-1)),newBullet);
}
else if(lists.peek().equalsIgnoreCase("ol"))
{
if(output.charAt(output.length()-1)!='\n')
output.append("\n");
int numberMargin=listItemIndent*(lists.size()-1);
if(lists.size()>2)
// Same as in ordered lists: counter the effect of nested Spans
numberMargin-=(lists.size()-2)*listItemIndent;
end(output,Ol.class,new LeadingMarginSpan.Standard(numberMargin));
}
}
else if(opening)
Log.d("TagHandler","Found an unsupported tag "+tag);
}
private static void start(final Editable text,final Object mark)
{
final int len=text.length();
text.setSpan(mark,len,len,Spanned.SPAN_MARK_MARK);
}
private static void end(final Editable text,final Class<?> kind,final Object... replaces)
{
final int len=text.length();
final Object obj=getLast(text,kind);
final int where=text.getSpanStart(obj);
text.removeSpan(obj);
if(where!=len)
for(final Object replace : replaces)
text.setSpan(replace,where,len,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
return;
}
private static Object getLast(final Spanned text,final Class<?> kind)
{
/*
* This knows that the last returned object from getSpans()
* will be the most recently added.
*/
final Object[] objs=text.getSpans(0,text.length(),kind);
if(objs.length==0)
return null;
return objs[objs.length-1];
}
private static class Ul
{
}
private static class Ol
{
}
}
I had the problem, that I always got an empty line after a list with #Kuitsis solution. I added a few lines in handleTag() and now the empty lines are gone:
#Override
public void handleTag(final boolean opening, final String tag, final Editable output, final XMLReader xmlReader) {
if (UL_TAG.equalsIgnoreCase(tag)) {
if (opening) { // handle <ul>
lists.push(new Ul());
} else { // handle </ul>
lists.pop();
if (output.length() > 0 && output.charAt(output.length() - 1) == '\n') {
output.delete(output.length() - 1, output.length());
}
}
} else if (OL_TAG.equalsIgnoreCase(tag)) {
if (opening) { // handle <ol>
lists.push(new Ol()); // use default start index of 1
} else { // handle </ol>
lists.pop();
if (output.length() > 0 && output.charAt(output.length() - 1) == '\n') {
output.delete(output.length() - 1, output.length());
}
}
} else if (LI_TAG.equalsIgnoreCase(tag)) {
if (opening) { // handle <li>
lists.peek().openItem(output);
} else { // handle </li>
lists.peek().closeItem(output, lists.size());
}
} else {
Log.d("TagHandler", "Found an unsupported tag " + tag);
}
}
this is a confirmation to what kassim has stated. there is fragmentation. i found how to resolve this. i have to rename <li> and ul to a custom tag. so:
myHTML.replaceAll("</ul>","</customTag>").replaceAll("<ul>","<customTag>");
//likewise for li
then in my handler i can look for that customTag (which does nothing) and make it do something.
//now my handler can handle the customtags. it was ignoring them after nougat.
public class UlTagHandler implements Html.TagHandler {
//for ul in nougat and up this tagHandler is completely ignored
#Override
public void handleTag(boolean opening, String tag, Editable output,
XMLReader xmlReader) {
if (tag.equals("customtag2") && opening)
output.append("\n\t\u25CF\t");
if (tag.equals("customtag2") && !opening)
output.append("\n");
}
}
this should make it work for all versions of android.

Categories

Resources