Is there any way to set Button text to capital letter for the first character and all text is cap?
Layout:
<Button
android:id="#+id/q1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="13sp"
android:textColor="#ffffff"
android:background="#drawable/ic_btn_q_normal" />
Activity:
final Button q1 = (Button) findViewById(R.id.q1);
q1.setText(answers[numbers.get(0)]);
q1.setOnClickListener(new OnClickListener() {
public void onClick(View v){
q1.setBackgroundResource(R.drawable.ic_btn_q_right);
}
});
answers[numbers.get(0)] is the text that I get from array list.
I have tried with q1.setAllCaps(true); but it's doesn't work for me.
Thanks.
You can use: WordUtils
method:
capitalize(String str):
Capitalizes all the whitespace separated words in a String.
or: capitalizeFully(String str)
Converts all the whitespace separated words in a String into capitalized words, that is each word is made up of a titlecase character and then a series of lowercase characters.
final Button q1 = (Button) findViewById(R.id.q1);
String label = answers[numbers.get(0)];
StringBuilder sb = new StringBuilder();
sb.append( label .substring(0,1) );
sb.append( label .substring(1).toLowerCase() );
label = sb.toString();
q1.setText(label);
q1.setOnClickListener(new OnClickListener() {
public void onClick(View v){
q1.setBackgroundResource(R.drawable.ic_btn_q_right);
}
});
Code for string conversion taken from: What is the simplest way to convert a Java string from all caps (words separated by underscores) to CamelCase (no word separators)?
Related
I want to thumbnail initials with two word for my image view like "Peter Parker" but am able to get only one word "P"while running code how can get second word after space my code is.
holder.imgName?.text=teamData[position].userImage.substring(0,1)
You can do it functional way:
val peterParker = "Peter Parker"
val initials = peterParker
.split(' ')
.mapNotNull { it.firstOrNull()?.toString() }
.reduce { acc, s -> acc + s }
println(initials) //PP
This would cover cases when a person's name consists of more than 2 words.
I have done some Trick & implemented this avatar with a Button lol ;p
create profile_bg.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid
android:color="#color/colorWhite"/>
<corners
android:radius="500dp"/>
</shape>
then main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#4300313A"
tools:context=".MainActivity">
<Button
android:onClick="clicked"
android:id="#+id/avatar"
android:clickable="false"
android:focusable="false"
android:textColor="#color/colorPrimary"
android:textSize="65sp"
android:focusableInTouchMode="false"
android:layout_width="150dp"
android:layout_height="150dp"
android:background="#drawable/profile_bg"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"/>
<EditText
android:id="#+id/edtname"
android:layout_below="#+id/avatar"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:textSize="18sp"
android:hint="Enter your name"/>
<Button
android:onClick="clicked"
android:textColor="#color/colorBackground"
android:text="Submit Name"
android:textStyle="bold"
android:focusableInTouchMode="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#+id/edtname"
android:layout_marginTop="50dp"/>
</RelativeLayout>
then in MainActivity.java (to split the string and get the first letter of each word ~ name in if condition with stringbuilder)
public class MainActivity extends AppCompatActivity {
EditText editText;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.edtname);
button = (Button) findViewById(R.id.avatar);
}
public void clicked(View view) {
String str = editText.getText().toString();
String[] strArray = str.split(" ");
StringBuilder builder = new StringBuilder();
//First name
if (strArray.length > 0){
builder.append(strArray[0], 0, 1);
}
//Middle name
if (strArray.length > 1){
builder.append(strArray[1], 0, 1);
}
//Surname
if (strArray.length > 2){
builder.append(strArray[2], 0, 1);
}
button.setText(builder.toString());
}
}
Hi you can using following way
String str = "FirstWord SecondWOrd";
String[] strArray = str.split(" ");
StringBuilder builder = new StringBuilder();
if (strArray.length > 0)
builder.append(strArray[0], 0, 1);
if (strArray.length > 1)
builder.append(strArray[1], 0, 1);
Log.d("New Text" , builder.toString());
it look's like your using substring to only grab the letters from position 0 to position 1, This is P in Petter
holder.imgName?.text=teamData[position].userImage
.substring(0,1)
If you'd like to grab the words Petter Parker, you have a few options.
• IndexOf & Substring - find the position of a string and get the subtext after.
• Substring - Subtext of string based on parameters
If you plan to change the text length at any stage, you'll need to find the start of the word ( int start = yourString.indexOf("Petter"));
and end of the word ( int end = yourString.indexOf(" "))
IndexOf will return the position of the first letter in your query - Your case it's P in Petter --- So start+"petter".length()
Here's an example of a barcode price checker app I'm working on
// STRING FORMAT 00000899999:0.99
String currentLine = "00000899999:0.99";
int breakPoint = currentLine.indexOf(":");
int end = currentLine.length();
int start = breakPoint + 1;
String Price = currentLine.substring(start,end);
Price will be starting after (:) With +1 or include (:) with no + 1 and end at the lines length.
I wrote an extension function in Kotlin to get initials for a name. You can use a custom view and use draw text and clip shape you want for avatar view.
val initials = "Vikas Patidar".asInitials()
fun String.asInitials(limit: Int = 2): String {
val buffer = StringBuffer()
trim().split(" ").filter {
it.isNotEmpty()
}.joinTo(
buffer = buffer,
limit = limit,
separator = "",
truncated = "",
) { s ->
s.first().uppercase()
}
return buffer.toString()
}
I have a requirement that Edittext should have all words start with Capital letter. If the user writes it in a smaller case(first letter of the word), then also it should be converted it into Uppercase.
I have done it in layout as below so far :
<EditText
android:id="#+id/edGymName"
style="#style/LoginRegisterEditText"
android:layout_marginTop="#dimen/size_10"
android:layout_toLeftOf="#+id/txtStatusGymStatus"
android:hint="#string/gym_tag"
android:inputType="textPersonName|textCapWords|textNoSuggestions"
android:maxLength="30" />
But, I don't want to allow the user to write the first letter of the word in the small letter. This is working but the user is able to write the first letter of the word in the small case. What if we forcefully do not allow it.
Set the input type to TYPE_CLASS_TEXT| TYPE_TEXT_FLAG_CAP_CHARACTERS.
android:inputType="textCapCharacters" for every character
android:inputType="textCapSentences" for senteces
android:inputType="textCapWords" for every words
Use this it will work.
android:inputType="textCapSentences"
In your case
<EditText
android:id="#+id/edGymName"
style="#style/LoginRegisterEditText"
android:layout_marginTop="#dimen/size_10"
android:layout_toLeftOf="#+id/txtStatusGymStatus"
android:hint="#string/gym_tag"
android:inputType="textCapSentences"
android:maxLength="30" />
Change input type to input type to TYPE_CLASS_TEXT| TYPE_TEXT_FLAG_CAP_CHARACTERS.
android:inputType="text|textCapCharacters"
or from java code
editText.setInputType(InputType.TYPE_CLASS_TEXT |InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS);
Statically (i.e. in your layout XML file): set
android:inputType="textCapSentences" on your EditText.
Programmatically: you have to include InputType.TYPE_CLASS_TEXT in the InputType of the EditText, e.g.
EditText editor = new EditText(this);
editor.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
User can manually change the text caps from Soft keyBoard to manage this case you can set a input filter. Android provide a AllCap filter for this.
edittext.setFilters(new InputFilter[] {new InputFilter.AllCaps()});
Setting filter will reset some other attribute which you set in manifest. So beware of it . Like if you have set maxlenth attribute set in xml then after setting filter you need to reset it at runtime otherwise it won't work . Below is and example.
editText.setFilters(new InputFilter[] {new InputFilter.AllCaps(),new InputFilter.LengthFilter(40)});
So the best way to do it Prevent all previous filter and just add a new one.
InputFilter[] oldFilters = editText.getFilters();
InputFilter[] newFilters = new InputFilter[oldFilters.length + 1];
System.arraycopy(oldFilters, 0, newFilters, 0, oldFilters.length);
newFilters[oldFilters.length] = new InputFilter.AllCaps();
editText.setFilters(newFilters);
This will forcefully retype your whole text/sentence from your editText and make every first letter of the word capital:
String oldText = ""; //this must be outside the method where the addTextChangedListener on the editText is set. (Preferrably outside the onCreate())
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
if (editable.toString().length() > 0 &&
!editable.toString().equals(oldText)) {
oldText = editable.toString(); //prevent infinite loop
editText.setText(capitalizeFirstLetterWord(editable.toString()));
editText.setSelection(editText.getText().length()); //set the cursor to the end of the editText
}
}
});
method called: (I've modified it a little bit, refer to the link)
/**
* reference: http://www.penguincoders.net/2015/06/program-to-capitalize-first-letter-of-each-word-in-java.html
*
* #param s sentence to be capitalize each first letter of each word
* #return capitalized sentence
*/
public static String capitalizeFirstLetterWord(String s) {
StringBuilder cap = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
try {
char x = s.charAt(i);
if (x == ' ') {
cap.append(" ");
char y = s.charAt(i + 1);
cap.append(Character.toUpperCase(y));
i++;
} else {
cap.append(x);
}
} catch (IndexOutOfBoundsException ignored) {
}
}
//finally, capitalize the first letter of the sentence
String sentence = cap.toString();
if (sentence.length() > 0) {
sentence = String.valueOf(sentence.charAt(0)).toUpperCase(); //capitalize first letter
if (cap.toString().length() > 1) { //check if there's succeeding letters
sentence += cap.toString().substring(1); //append it also
}
}
return sentence;
}
I am new to android and am trying to make an app where the user inputs an array in a text box with inputType = textMultiLine. The problem is that I want to make it so that whenever user hits enter, the app takes input of the next array element and not treat the entire text in the textbox as one element. The code is as below :
EditText input = findViewById(R.id.inputtext);
Button show = findViewById(R.id.button);
TextView output = findViewById(R.id.output);
String [] name = new String[3];
for (int i = 0 ; i < 3 ; i++)
{
name[i] = input.getText().toString();
output.setText(name[i]);
}
But whenever i try to take name[1] after hitting enter the app doesnt treat the next line as name[2] but instead treats it as name[1]. For example if type the names john,steve and frank, then i should get an array that is like this :
name[0] = john
name[1] = steve
name[2] = frank
but instead whenever I typejohn,press enter,type steve, press enter and type frank the app treats it as :
name[0] = john
steve
frank
also if i set the output to something like this :
output.setText(name[i] + i)
instead of getting an oupt like this :
john 0
steve 1
frank 2
I get an output like this :
john
steve
frank2
Any and all help would be much appreciated.
Thanks
======================================================================================================================================================
EDIT 1
I tried this code but didn't work:
String name[] = input .getText().toString().split("\\r?\\n");
for (int i = 0 ; i < name.length; i++)
{
output.setText(name[i]);
}
Still get only frank when I input john,steve and frank
If you want to put each line to different array item :
String [] name = input.getText().toString().split("\n");
input.getText().toString() gives you string containing whole EditText content with lines separated by new line - "\n". You need to split this string to get each line.
try below code
String name[] = input .getText().toString().split("\\r?\\n");
String disp="";
for (int i = 0 ; i < name.length; i++)
{
disp += name[i] +"\n";
}
output.setText(disp);
Maybe the following example will be useful:
XML file
<?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:gravity="center"
android:orientation="vertical">
<EditText
android:id="#+id/edit_text"
style="#style/Widget.AppCompat.EditText"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_marginBottom="100dp"
android:inputType="textMultiLine"/>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show"/>
<TextView
android:id="#+id/text_view"
style="#style/Widget.AppCompat.EditText"
android:layout_width="300dp"
android:layout_height="wrap_content"/>
</LinearLayout>
Java Code
final EditText input = findViewById(R.id.edit_text);
final Button show = findViewById(R.id.button);
final TextView output = findViewById(R.id.text_view);
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
final String inputString = input.getText().toString();
if (!TextUtils.isEmpty(inputString)) {
final String newLine = System.getProperty("line.separator");
final String[] inputText = inputString.split(newLine);
String outputText = "";
for (int i = 0; i < inputText.length; i++) {
outputText += inputText[i];
if (i != inputText.length - 1) {
outputText += newLine;
}
}
output.setText(outputText);
}
}
});
}
You can download de APK here or here the complete source code
(another way:simple!) In the following code it is not necessary to make a split on the input text.
final EditText input = findViewById(R.id.edit_text);
final Button show = findViewById(R.id.button);
final TextView output = findViewById(R.id.text_view);
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
final String inputString = input.getText().toString();
if (!TextUtils.isEmpty(inputString)) {
output.setText(inputString);
}
}
});
Note that, your code is wrong, because in for each loop, you override the text was setted in the previous loop.
Not asked a question in a while so it's been long overdue!
I am creating an app where job items can be created onClick, with each new row containing a Description(EditText), a Price(EditText) and a button to delete the current row, but I am having trouble when getting the values from the EditText fields when there is more than one row - it just returns the values of the newest row.
Aside from the 'Job List Container', the views are created dynamically so pardon the lack of XML, but the structure of what I am trying to achieve is as follows, where clicking the Add button adds a row (this can be multiple rows) and clicking the submit button takes all of the Description and Price values and processes them (adds the prices and adds the job to the DB):
...and this is the code I've written for it called from the addNewJobRow onClick listener (all together for simplicity):
private void addJobItem() {
//Create a new row container
final LinearLayout jobRowContainer = new LinearLayout(this);
//Create a new EditText for the Description
final EditText description = new EditText(this);
description.setHint("Description...");
description.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
1.0f
));
//Create an EditText for the Price
final EditText price = new EditText(this);
price.setHint("00.00");
//Create a new button to delete the row
Button delete = new Button(this);
delete.setBackgroundColor(Color.RED);
delete.setText("X");
//Add Description, Price and Delete to the row container
jobRowContainer.addView(description);
jobRowContainer.addView(price);
jobRowContainer.addView(delete);
//Add the Row Container to the Jobs List Container
ll_jobListContainer.addView(jobRowContainer);
//Get the values of the Description and Price, for each row
btn_JobSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < ll_jobListContainer.getChildCount(); i++) {
for(int j = 0; j < jobRowContainer.getChildCount(); j++) {
if (jobRowContainer.getChildAt(i) instanceof EditText){
String descriptionString = description.getText().toString();
String priceString = price.getText().toString();
System.out.println("z! " + descriptionString + " # " + priceString);
}
}
}
}
});
}
I have tried a couple of iterations of this with and without the nested FOR loops and with and without the use of instanceof, but all it does is print out the newest row.
So, if I have multiple job rows, how can I get all of the values as required?
Thanks for your time and all that nice stuff xxx
The basic problem is that you're using only the last instance of description and price instead of each rows instance. (This may be what Dmitry is saying as well). To fix it, you need to get the input for each row. Here's one way.
Set an ID for description & price. (You can't just use '1' or '2', it needs to be a resource type ID so it is guaranteed to be unique). I made a dummy layout file of a row & assigned IDs in that to the 2 EditTexts. There may be a better way to do it. So anyway, add these 2 lines in your declarations
descripton.setId(R.id.description); and price.setId(R.id.price);
Now this is your onClick()
public void onClick(View v) {
for (int i = 0; i < ll_jobListContainer.getChildCount(); i++) {
LinearLayout currentRow = (LinearLayout)ll_jobListContainer.getChildAt(i);
EditText editText = (EditText)currentRow.findViewById(R.id.description);
String descriptionString = editText.getText().toString();
editText = (EditText)currentRow.findViewById(R.id.price);
String priceString = editText.getText().toString();
Log.d(TAG, "z! " + descriptionString + " # " + priceString);
}
}
EDIT: I didn't want to change this answer since it had already been accepted so I've put a more concise solution in another answer.
Of cause, your last setOnClickListener takes strings
String descriptionString = description.getText().toString();
String priceString = price.getText().toString();
Where description and price - is fields in the function (last edittexts).
The good way to do that is to use RecyclerView/ListView, in "onTextChangeListner" of ViewHolder save new text to model of this object and print all text from your models, not directly from views.
I normally try to answer only question that was asked rather than change code that's not necessary. However, in this case, since I had created a dummy layout just to get Resource IDs, I wonder if that layout file could be put to use. I had started to change my answer but original one was accepted before I could make the changes. I've put a different version of the solution here. I didn't want to modify an answer that had already been accepted.
private void addJobItem() {
//Create a new row container
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout jobRowContainer = (LinearLayout)inflater.inflate(R.layout.row_layout, null);
//Add the Row Container to the Jobs List Container
ll_jobListContainer.addView(jobRowContainer);
//Get the values of the Description and Price, for each row
btn_JobSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < ll_jobListContainer.getChildCount(); i++) {
LinearLayout currentRow = (LinearLayout)ll_jobListContainer.getChildAt(i);
EditText editText = (EditText)currentRow.findViewById(R.id.description);
String descriptionString = editText.getText().toString();
editText = (EditText)currentRow.findViewById(R.id.price);
String priceString = editText.getText().toString();
Log.d(TAG, "z! " + descriptionString + " # " + priceString);
}
}
});
}
row_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/single_row">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Description..."
android:id="#+id/description"
/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="00.00"
android:id="#+id/price"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/holo_red_dark"
android:text="X"
android:id="#+id/clear_button"
/>
</LinearLayout>
I have already used following options to make each starting letter of a word Uppercase
<EditText
android:inputType="text|textCapWords"/>
While typing the user has option on the keyboard to change the case of letter i.e. the user with this option can easily type lowercase letters.
Further,I want text on my EditText to be on this format
Each Starting Letter Of A Word Must Be In Uppercase And All Other Letter Of The Word Be In Lowercase.
Meaning,when the user inputs
each StArting LeTTer of a word musT be in uppercase and all other leTTer of the word be in lowercase
, it will be automatically converted to above format.
I have tried using TextWatcher and string.split(\\s+) to get all the words and then make each and every word to follow the above format. But I always end up getting error.
So if there is any solution,it would be great.I want this to work in the manner InputFilter.AllCaps.
This is my code so far
private void changeToUpperCase(String inputString) {
if (inputString != null && inputString.trim().length() > 0) {
// businessName.addTextChangedListener(null);
String[] splitString = inputString.split("\\s+");
int length = splitString.length;
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < length; i++) {
String convertedString = splitString[i];
stringBuffer.append(Character.toUpperCase(convertedString
.charAt(0)));
stringBuffer.append(convertedString.substring(1).toLowerCase());
stringBuffer.append(" ");
}
Log.i("changed String", stringBuffer.toString());
// businessName.setText(stringBuffer.toString());
stringBuffer.delete(0, stringBuffer.length());
stringBuffer = null;
// businessName.addTextChangedListener(this);
}
}
This function I am calling from TextWatcher, afterTextChanged(Editable s)
In the layout xml, add android:capitalize="sentences"
The options for android:capitalize are following :
android:capitalize="none" : which won't automatically capitalize anything.
android:capitalize="sentences" : which will capitalize the first word of each sentence.
android:capitalize="words" : which will capitalize the first letter of every word.
android:capitalize="characters" : which will capitalize every character.
Update:
As android:capitalize is deprecated now need to use:
android:inputType="textCapWords"
change your input type programmatically.
If you are in View layout than use this code
EditText text = new EditText(context);
text.setInputType(InputType.TYPE_TEXT_FLAG_CAP_WORDS); // which will capitalize the first letter of every word.
text.setInputType(InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS); //which will capitalize every character.
text.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES); //which will capitalize the first word of each sentence.
addView(text);
and if you are in Activity
EditText text = new EditText(this);
text.setInputType(InputType.TYPE_TEXT_FLAG_CAP_WORDS); // which will capitalize the first letter of every word.
text.setInputType(InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS); //which will capitalize every character.
text.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES); //which will capitalize the first word of each sentence.
setContentView(text);
To make first letter capital of every word:
android:inputType="textCapWords"
To make first letter capital of every sentence:
android:inputType="textCapSentences"
To make every letter capital:
android:inputType="textCapCharacters"
Try this,
txtView.setText(WordUtils.capitalize("text view")
WordUtils.java
public class WordUtils {
public static String capitalize(String str) {
return capitalize(str, (char[]) null);
}
public static String capitalize(String str, char... delimiters) {
int delimLen = delimiters == null ? -1 : delimiters.length;
if (!TextUtils.isEmpty(str) && delimLen != 0) {
char[] buffer = str.toCharArray();
boolean capitalizeNext = true;
for (int i = 0; i < buffer.length; ++i) {
char ch = buffer[i];
if (isDelimiter(ch, delimiters)) {
capitalizeNext = true;
} else if (capitalizeNext) {
buffer[i] = Character.toTitleCase(ch);
capitalizeNext = false;
}
}
return new String(buffer);
} else {
return str;
}
}
private static boolean isDelimiter(char ch, char[] delimiters) {
if (delimiters == null) {
return Character.isWhitespace(ch);
} else {
char[] arr$ = delimiters;
int len$ = delimiters.length;
for (int i$ = 0; i$ < len$; ++i$) {
char delimiter = arr$[i$];
if (ch == delimiter) {
return true;
}
}
return false;
}
}
}
android:capitalize is deprecated. Use inputType instead.