how to make thumbnail image with initials two char from name android? - android

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()
}

Related

Inputting Array In Multiline Text In Android

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.

How to format single textview like below in android without using \n or html format?

This type of formatting i need i don't want to use \n or br because my string is dynamic and i want to fix any text in this this format
This is my first textview
This is my second
textview this
is my third
textview
You can do it programmatically using this function
val text = "This is my first text view this is my second textview this is my third textview"
textView.text = proxyWifi.textFormation(text)
copy/paste this code do your project :)
public String textFormation(String text){
String result = "";
String[] sentenceWords = text.split(" ");
List<String> newSentenceWords = new ArrayList<>();
textRec(sentenceWords, newSentenceWords, sentenceWords.length -1, 0, "");
int spacing = 0;
for(int i = newSentenceWords.size() -1 ; i >= 0 ; i--){
if(i == newSentenceWords.size() -1)
result = newSentenceWords.get(i);
else{
result += "\n";
spacing += (newSentenceWords.get(i + 1).length() - newSentenceWords.get(i).length())/2;
for(int j = 0 ; j < spacing ; j++){
result += " ";
}
result += newSentenceWords.get(i);
}
}
return result;
}
public void textRec(String[] words, List<String> newWords, int indexWords, int indexNewWords, String sentence){
Log.e("sentence", sentence);
if(indexWords >= 0){
if(indexNewWords == 0) {
newWords.add(words[indexWords]);
textRec(words, newWords, indexWords - 1, ++indexNewWords, "");
}else{
if(newWords.get(indexNewWords - 1).length() >= sentence.length())
if(sentence.isEmpty())
textRec(words, newWords, indexWords - 1, indexNewWords, words[indexWords]);
else
textRec(words, newWords, indexWords - 1, indexNewWords, words[indexWords] + " " + sentence);
else {
newWords.add(sentence);
textRec(words, newWords, indexWords , ++indexNewWords, "");
}
}
}else{
if(sentence.isEmpty()){
return;
}else{
newWords.set(indexNewWords - 1 ,sentence + " " + newWords.get(indexNewWords - 1)) ;
}
}
}
OUTPUT
There is no default implementation for this. Also, you can't find the line number to do this.
So you have to split the sentence into multi lines.Use \n for next line. Set gravity center to your textView.
if you use \n then your next line will be start from
This is my first textview
<here>
<not here>
So, basically you need multiple TextViews.
First devide your text String to multiple parts(Note:- (n+1)th part should be less than nth part and deff. should be both end space).
Second Create a LinearLayout with vertical orientation and center gravity.
Third loop on that array.
and in loop create a new textview with gravity center, and set the text to it.
and add this TV to linearLayout.
thats it.
I tried to give you result as you want
This may work
activity_main.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:gravity="center"
tools:context="com.ap.mytestingapp.MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/strTV"
android:text="hello world!"
android:gravity="center" />
</RelativeLayout>
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.strTV);
//pass string whatever you want to show
String apStr = printString("This is my first textview This is my second textview this is my third textview");
//you need to define text size according to your requirement
// I took here 25
tv.setTextSize(25);
tv.setText(apStr);
}
private String printString(String responseString) {
String str = responseString;
String resultStr = "";
//you need to define cutLength Value according to your textView's textSize
// I took it 35 when textView's textSize is 25
int cutLength = 35;
int count = 0;
int from = 0;
for(int i = 0 ; i < str.length(); i++){
//increment of count
count++;
//check count value with cutLength so that we can add \n to string
if(count == cutLength){
// adding \n to substring
resultStr = resultStr + str.substring(from, i) + "\n";
// assigning from = i
from = i;
// reduce cutLength value
cutLength = cutLength-10;
// assigning count = 0
count = 0;
} else if(i == str.length()-1){
// adding \n to substring
resultStr = resultStr + str.substring(from) + "\n";
}
}
//return resulting string
return resultStr;
}
}

Getting values of EditTexts from multiple Layouts in Android not working?

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>

How to make a Textview display a number?

I'm new to Android development. I tried to make a Textview display a text or number and it crashes. Please Help.
This is the button in activity_main.xml:
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_alignParentBottom="true"
android:text="#string/Change"
android:onClick="change"/>
and this is the Main Activity:
public void change(){
TextView tv = new TextView(this);
tv.setText("" + 4);
}
the application crashes when i start it. I wanted to create a basic calculator with two text boxes and a button which when pressed adds the value in two text boxes and display it. can anybody tell me where I am going wrong with the code?
public void change()
{
TextView tv = new TextView(this);
tv.setText("4");
}
and if it is any kind of integer variable, then
public void change()
{
TextView tv = new TextView(this);
tv.setText("" + integer_variable);
}
and also, check if the textView is plumbed with the code
TextView tv = (TextView) findViewById(R.Id.textView1);
should have worked fine, I hope.. :)
If it crashes again, then the information in the question may be incomplete.
Happy Coding..!
public void change(){
TextView tv =(TextView)findViewById(R.id.textView1);
tv.setText(Integer.toString(4));
}
layout_contact.xml:
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:text="#string/number1" />
strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="number1">0091010</string>
</resources>
ContactFragment.java:
String num = "0091010";
textView8.setText(someContactNum);
Output:
0091010
You have to give id of the text view properly in the xml like
<TextView
....
android:id="#+id/tvID"/>
Check it you gave it properly or not..
Otherwise here share your textview code from your xml file..
And also checkit, you import the Textview in your code or not like this:
import android.widget.TextView;
Here is the answer for how to display the dynamic numbers in a single text view
StringBuilder stringBuilder = new StringBuilder();
for (int j = fromNumber; j <= toNumber; j++) {
for (int i = 2; i <= j / 2; i++) {
if (j % i == 0) {
isPrimeNumber = false;
break;
} else {
isPrimeNumber = true;
}
}
if (isPrimeNumber) {
stringBuilder.append(j);
stringBuilder.append(",");
} else {
}
}
tvResult.setText(stringBuilder.toString());

Android: Is there a method equivalent to XML android:digits?

In my layout xml, I use the following to define an EditText that can display currency.
<EditText
android:id="#+id/et1"
android:layout_width="210dp"
android:layout_height="wrap_content"
android:imeOptions= "actionNext"
android:inputType="phone"
android:digits="0123456789.,$" >
However, this is not localized. I want to be able to use the symbol returned by NumberFormat.getCurrencyInstance().getCurrency().getSymbol(); in place of the $ in android:digits.
What I don't know is how to set android:digits from within my program.
Solved thanks to Agarwal. I just need to read the documentation more thoroughly.
Try this:
<EditText
android:inputType="number"
android:digits="0123456789."
/>
From Code:
weightInput.setKeyListener(DigitsKeyListener.getInstance("0123456789."));
But, it allows the user to include several "."
You can also do this for accepting on digits...
EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
Yes you can check here
http://developer.android.com/reference/android/widget/EditText.html
for almost every attribute there is equivalent method present.
setKeyListener(KeyListener)
For those interested, here is how I solved the original question. It is the complete implementation of a currency edit text that can handle multiple locales. Still may be some problems (Doesn't seem to display Japanese currency symbol correctly, and I can't get the keyboard I want (12_KEY)), but otherwise, some may find this helpful.
public class CurrencytestActivity extends Activity
{
private static final Integer MAX_VALUE_DIGITS = 9;
EditText et1;
NumberFormat mCurrencyFormatter;
CurrencyTextWatcher tw;
#Override public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get info about local currency
mCurrencyFormatter = NumberFormat.getCurrencyInstance();
int fractionDigits = mCurrencyFormatter.getCurrency().getDefaultFractionDigits();
et1 = (EditText)findViewById(R.id.et1); // Get a handle to the TextEdit control
// Add local currency symbol to digits allowed for EditText display and use
// DigitsKeyListener to tell the control. Unfortunately, this also resets the inputType
// that is specified in the XML layout file. Don't know how to fix that yet.
// Also, this doesn't seem to work for Japanese (probably due to UNICODE or something).
// The symbol gets added to displayCharacters, but the EditText doesn't use it.
String displayCharacters = "0123456789.," + mCurrencyFormatter.getCurrency().getSymbol();
et1.setKeyListener(DigitsKeyListener.getInstance( displayCharacters ));
// Add a text watcher to the EditText to manage currency digit entry. The TextWatcher
// won't allow the symbol or decimal or comma to be entered by the user, but they are
// still displayed when the result is formatted in afterTextChanged().
tw = new CurrencyTextWatcher( MAX_VALUE_DIGITS, fractionDigits );
et1.addTextChangedListener( tw );
et1.setCursorVisible( false );
((Button)findViewById(R.id.button1)).setOnClickListener(onButtonClick);
}
public class CurrencyTextWatcher implements TextWatcher
{
boolean mEditing; // Used to prevent recursion
Double mAmount;
int mDigitCount, mMaxDigits, mFractionDivisor;
public CurrencyTextWatcher( int maxDigits, int fractionDigits )
{
mEditing = false;
mFractionDivisor = (fractionDigits == 0) ? 1 : ((fractionDigits == 1) ? 10 : 100);
mAmount = 0.0;
mDigitCount = 0;
mMaxDigits = maxDigits;
}
public synchronized void afterTextChanged(Editable s)
{
// Don't update EditText display if we are editing
if ( !mEditing )
{
// Under cover of mEditing, update the EditText display with
// the newly formatted value
mEditing = true;
s.replace( 0, s.length(), mCurrencyFormatter.format( mAmount ));
mEditing = false;
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
public double GetAmount() { return( mAmount ); }
public void onTextChanged(CharSequence s, int start, int before, int count)
{
if ( !mEditing )
{
// Added a digit to the value
if (( count == 1 ) && ( mDigitCount < mMaxDigits ))
{
// Obtain the added character
CharSequence x = s.subSequence( start, start + count );
// Ignore any characters other than number digits for addition to value
if (( x.charAt( 0 ) >= '0') && ( x.charAt( 0 ) <= '9'))
{
// Multiply by ten to shift existing digits to the left and
// add in the new digit as the decimal place appropriate to this currency
mAmount = (mAmount * 10) + (Double.parseDouble( x.toString() ) / mFractionDivisor);
mDigitCount += 1;
}
}
// Delete last digit from the value
else if (( count == 0 ) && ( mDigitCount > 0))
{
// Subtract the amount of the last digit and divide by ten to
// effectively delete the last character entered
mAmount -= (mAmount % (0.001 * mFractionDivisor) );
mAmount /= 10;
mDigitCount -= 1;
}
}
}
}
private View.OnClickListener onButtonClick = new View.OnClickListener()
{
#Override public void onClick(View v)
{
if (v.getId() == R.id.button1 )
{
// Get the value from the textwatcher and display it.
double mAmountTest = tw.GetAmount();
((TextView)findViewById(R.id.tv1)).setText(mCurrencyFormatter.format( mAmountTest ));
}
}
};
}
And the accompanying XML layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center|top"
android:orientation="vertical" >
<EditText
android:id="#+id/et1"
android:layout_width="210dp"
android:layout_height="wrap_content"
android:imeOptions= "actionNext"
android:inputType="phone" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Extract from TextWatcher" />
</LinearLayout>

Categories

Resources