Ok,so I"m trying to make a Currency Converter between dollars and euros based on a tutorial I found on the web.The problem is that the tutorial is relying on 2 radio buttons to switch between the conversion, a reference for order stating to the program which method to call first.I want the program to make that conversion independetly from the two radio buttons and instantaneously,for instance if I write a number in the euro or dollar editText view...then clicking on the convert button will make the appropriate conversion.But I cannot because there are 2 methods and unless a have a way to display their input simultaneously it won't work.So my question is how ca I update the two editText views simultaneously when I press the convert button?Thank you
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class ConvertorActivity extends Activity {
TextView dollars;
TextView euros;
Button convert;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
dollars = (TextView)this.findViewById(R.id.dollars);
euros = (TextView)this.findViewById(R.id.euros);
convert = (Button)this.findViewById(R.id.convert);
convert.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
convertBoth();
}
});
}
public void convertBoth(){
convertDollarsToEuros();
convertEurosToDollars();
}
protected void convertDollarsToEuros() {
double val = Double.parseDouble(dollars.getText().toString());
// in a real app, we'd get this off the 'net
euros.setText(Double.toString(val*0.67));
}
protected void convertEurosToDollars() {
double val = Double.parseDouble(euros.getText().toString());
// in a real app, we'd get this off the 'net
dollars.setText(Double.toString(val/0.67));
}
}
I think what you want is this:
If the user changed the dollar amount, convert it to euro
If the user changed the euro amount, convert it to dollar
If that's the case, you can add a member variable mLastEditedViewId and use a TextWatcher to track which field was last changed. Then, onClick, call convertDollarsToEuros() or convertEurosToDollars accordingly.
In onCreate:
dollars.addTextChangedListener(new MyTextWatcher(dollars));
euros.addTextChangedListener(new MyTextWatcher(euros));
convert.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
switch (mLastEditedViewId) {
case R.id.dollars:
convertDollarsToEuros();
break;
case R.id.euros:
convertEurosToDollars();
break;
}
}
});
Define an inner class for the TextWatcher:
private class MyTextWatcher implements TextWatcher {
private int mTextViewId;
public MyTextWatcher(TextView view) {
mTextViewId = view.getId();
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
mLastEditedViewId = mTextViewId;
}
public void afterTextChanged(Editable s) {
}
}
Related
So I'm in a basic part of my application I'm wanting to make. I've never gotten this error before, and I don't know what's going on. My .setText is throwing an error saying "setText cannot be resolved or is not a field" I've looked around and haven't been able to find my problem. I believe I'm doing it correctly. If anyone could help me out that'd be great!
MainActivity.java:
public class MainActivity extends Activity {
final TextView loading_Text = (TextView)findViewById(R.id.textView4);
final EditText name_Edit = (EditText)findViewById(R.id.editText1);
//String Values
String Age="";
String Name = name_Edit.getText().toString();
//Int Values
int Gender = 0; //1 male | 2 female
int Group = 0; //Different groups for ages and genders
int save_Info = 0; //save info to phone
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button male_Button= (Button)findViewById(R.id.button1);
Button female_Button = (Button)findViewById(R.id.button2);
male_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Gender++;//Adds one to show this user is a male.
loading_Text.setText=(Name);
}
});
}
I saw two problems:
First:
loading_Text.setText=(Name);
Should be
loading_Text.setText("The text you want to set");
You'll need to take a look at the API document to see how to call the method.
Second:
Move these part:
final TextView loading_Text = (TextView)findViewById(R.id.textView4);
final EditText name_Edit = (EditText)findViewById(R.id.editText1);
//String Values
String Age="";
String Name = name_Edit.getText().toString();
inside your onCreate, like this:
public class MainActivity extends Activity {
TextView loading_Text;
EditText name_Edit;
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loading_Text = (TextView)findViewById(R.id.textView4);
name_Edit = (EditText)findViewById(R.id.editText1);
Or you'll get NullPointerException.
This is because you were trying to reach the View's property before the view is being initialized. View will be initialized after setContentView, and what you were intend to do was findViewById from R.layout.activity_main before it had been loaded.
Similarly, you'll need to move this call of method:
String Name = name_Edit.getText().toString();
somewhere after setContentView.
setText is a function. So you would need to pass name as a argument.
like loading_Text.setText(Name);
Change
loading_Text.setText=(Name);
to this:
loading_Text.setText(Name);
Also, if you don't see anything in the textview, it is because you are getting the edittext's text before you even create your views, I use an on edittext listener like this to refresh the String when the edit text is changed:
name_Edit.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
Name = name_Edit.getText().toString();
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {}
});
I hope this works for you :)
Until three weeks ago I knew nothing about developing applications for android, and with very basic Java background.
However, I took up the interest, and I'm now tying to develop a simple application that performs basic arithmetic operations.
What I would like the application to do is take in figures input by the user, up to 20 pairs, multiply each pair separately, and then add the results.
I have gotten through the multiplication of the pairs, but can't get onto adding up the results.
This is what I have so far for the multiplication part, and it works okay....
public class CalcAlgorithm extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
final String LOG_TAG = "MainScreen";
super.onCreate(savedInstanceState);
setContentView(R.layout.calc_algorithm);
final EditText value1=(EditText) findViewById(R.id.value1);
final EditText value2=(EditText) findViewById(R.id.value2);
final EditText value3=(EditText) findViewById(R.id.value3);
final EditText value4=(EditText) findViewById(R.id.value4);
final EditText value5=(EditText) findViewById(R.id.value5);
final EditText value6=(EditText) findViewById(R.id.value6);
final EditText value7=(EditText) findViewById(R.id.value7);
final EditText value8=(EditText) findViewById(R.id.value8);
final EditText value9=(EditText) findViewById(R.id.value9);
final EditText value10=(EditText) findViewById(R.id.value10);
final TextView result=(Button) findViewById (R.id.multiplyValues);
final TextView result2=(Button) findViewById (R.id.multiplyValues2);
final TextView result3=(Button) findViewById (R.id.multiplyValues3);
final TextView result4=(Button) findViewById (R.id.multiplyValues4);
final TextView result5=(Button) findViewById (R.id.multiplyValues5);
final TextView result6=(Button) findViewById (R.id.addButton);
Button multiplyButton = (Button)findViewById(R.id.multiplyValues);
multiplyButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
try {
int val1=Integer.parseInt(value1.getText().toString());
int val2=Integer.parseInt(value2.getText().toString());
Integer answer = val1*val2;
result.setText(answer.toString());
} catch (Exception e) {
Log.e(LOG_TAG, "Failed to multiply numbers",e);
}
}
});
Button multiplyButton2 = (Button) findViewById(R.id.multiplyValues2);
multiplyButton2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
int val3 = Integer.parseInt(value3.getText().toString());
int val4 = Integer.parseInt(value4.getText().toString());
Integer answer = val3 * val4;
result2.setText(answer.toString());
} catch (Exception e) {
Log.e(LOG_TAG, "Failed to multiply numbers",e);
}
}
});
Button multiplyButton3 = (Button) findViewById(R.id.multiplyValues3);
multiplyButton3.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
int val5 = Integer.parseInt(value5.getText().toString());
int val6 = Integer.parseInt(value6.getText().toString());
Integer answer = val5 * val6;
result3.setText(answer.toString());
} catch (Exception e) { Log.e(LOG_TAG, "Failed to multiply numbers",e);}}
});
Button multiplyButton4 = (Button) findViewById(R.id.multiplyValues4);
multiplyButton4.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
int val7 = Integer.parseInt(value7.getText().toString());
int val8 = Integer.parseInt(value8.getText().toString());
Integer answer = val7 * val8;
result4.setText(answer.toString());
} catch (Exception e) { Log.e(LOG_TAG, "Failed to multiply numbers",e);}}
});
Button multiplyButton5 = (Button) findViewById(R.id.multiplyValues5);
multiplyButton5.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
int val9 = Integer.parseInt(value9.getText().toString());
int val10 = Integer.parseInt(value10.getText().toString());
Integer answer = val9 * val10;
result5.setText(answer.toString());
} catch (Exception e) {
Log.e(LOG_TAG,"Failed to multiply number",e);
}
}
});
Is this the right path? And, i realize that there is a way of summarising the code into fewer lines and not as i have it. Could someone please show me how I can go about having fewer lines of code, and then adding up the results all at once?
After adding the values, I'd again like to perform some more (basic) operations on the results, but i think after I have known how to add the results, I should be able to figure my way from there.
**Perhaps i should point out that i would require the addition to be done once separately i.e on clicking of an added button (TotalSum,maybe) separately and not progressively as the multiplication goes on, such that the user can see the multiplied results for each pair of figures entered, and the total of all paired results on clicking a separate button..
It would also be of immense help if i could get links to some books/documentation/videos that could help with arithmetic functions in writing android applications.
Any help will be greatly appreciated guys. :)
You could add a calculateResultSum() method, which you call at the end of each onClick method with does something like
void calculateResultSum() {
Integer res1 = Integer.parse(result.getText.toString());
// .. get all the other results
Integer finalResult = res1 + res2 + res2 + res4 + res5;
//do something with the result
}
BUT your approach is very redundant, i.e. you have the same code in all of you onClick methods. This is considered bad code style, you should try to extract the actual processing of the numbers into one single method and call this method from each of the listeners, for example
void addNumbers(TextView tv1, TextView tv2, TextViev res){
try {
Integer val1=Integer.parseInt(value1.getText().toString());
Integer val2=Integer.parseInt(value2.getText().toString());
Integer answer = val1*val2;
res.setText(answer.toString());
} catch (Exception e) { Log.e(LOG_TAG, "Failed to multiply numbers",e);}}
}
and set the onClicks to
multiplyButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
addNumbers(value1,value2,result);
calculateResultSum();
});
with the corresponding views for each Button. Hope I could help.
If I understood correctly, here is the solution.
Create a class variable like private int total=0; and in each setOnClickListener add your answers to this variable.
Integer answer = val1*val2;
total += answer;
Also instead of using 5 Button and 10 TextViews you can do this with simply one Button and one TextView storing results in another TextView but you said you are practicing, if it is just to practice it should be alright.
package com.example.calc;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText num1_edt=(EditText)findViewById(R.id.num1_edt);
final EditText num2_edt=(EditText)findViewById(R.id.num2_edt);
final Button add_btn=(Button)findViewById(R.id.add_btn);
findViewById(R.id.sub_btn);
findViewById(R.id.mul_btn);
findViewById(R.id.div_btn);
add_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int a=Integer.parseInt(num1_edt.getText().toString());
int b=Integer.parseInt(num2_edt.getText().toString());
Integer n=a*b;
Toast.makeText(getApplicationContext(),"Your Num Is:"+n.toString(),Toast.LENGTH_LONG).show();
}
});
}
}
Could you guys lend me some fresh eyes and tell me what where I should look to find the missing link? I am trying to do a mortgage calculation by pulling value from purchasePrice, downPayment, and interestRate EditText fields to do the calculation. I tested the updateStandand() by setting the TextEdit field to interest rate. However, when I run the app in AVD, if I type a purchase price, the monthly payment field would reflect the price. If i move down to interest rate field and type in a number, the monthly payment field would change to the value of the interest rate.
Thank you!
package com.example.mortgagecalc;
import com.example.mortgagecalc.R.string;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.text.Editable;
public class Main extends Activity {
private static final String PURCHASE_AMOUNT = "PURCHASE_AMOUNT";
private static final String CUSTOM_LENGTH = "CUSTOM_LENGTH";
private static final String DOWN_PAYMENT = "DOWN_PAYMENT";
private static final String INTEREST_RATE = "INTEREST_RATE";
private int currentPurchaseAmount; //purchase amount entered by user
private int currentCustomLength; //length of loan set with SeekBar
private int currentDownPayment; //down payment entered by user
private double currentInterestRate; //interest rate entered by user
private EditText purchaseAmountEditText; //accepts user input for purchase amount
private EditText downPaymentEditText; //accepts user input for down payment amount
private EditText interestRateEditText; //accepts user input for interest rate
private EditText tenYearEditText; //display monthly payment for 10yr. loan
private EditText twentyYearEditText; //display monthly payment for 20yr. loan
private EditText thirtyYearEditText; //display monthly payment for 30yr. loan
private EditText customMonthlyEditText; //display monthly payment for custom length
private TextView customLengthTextView; //display custom loan length
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//check if app just started or being restored from memory
if (savedInstanceState == null) //app just started running
{
currentPurchaseAmount = 0; //initialize to zero
currentCustomLength = 10; //initialize custom loan length to 10
currentDownPayment = 0; //initialize to zero
currentInterestRate = 0.0; //initialize to zero
}
else
{
currentPurchaseAmount = savedInstanceState.getInt(PURCHASE_AMOUNT);
currentCustomLength = savedInstanceState.getInt(CUSTOM_LENGTH);
currentDownPayment = savedInstanceState.getInt(DOWN_PAYMENT);
currentInterestRate = savedInstanceState.getDouble(INTEREST_RATE);
}
purchaseAmountEditText = (EditText) findViewById(R.id.purchaseAmountEditText);
downPaymentEditText = (EditText) findViewById(R.id.downPaymentEditText);
interestRateEditText = (EditText) findViewById(R.id.interestRateEditText);
tenYearEditText = (EditText) findViewById(R.id.tenYearEditText);
twentyYearEditText = (EditText) findViewById(R.id.twentyYearEditText);
thirtyYearEditText = (EditText) findViewById(R.id.thirtyYearEditText);
customMonthlyEditText = (EditText) findViewById(R.id.customMonthlyEditText);
customLengthTextView = (TextView) findViewById(R.id.customMonthlyTextView);
purchaseAmountEditText.addTextChangedListener(textWatcher);
downPaymentEditText.addTextChangedListener(textWatcher);
interestRateEditText.addTextChangedListener(textWatcher);
SeekBar customSeekBar = (SeekBar) findViewById(R.id.customSeekBar);
customSeekBar.setOnSeekBarChangeListener(customSeekBarListener);
}
private void updateStandard(){
double interestRate = currentInterestRate;
//double loanPrinciple = currentPurchaseAmount - currentDownPayment;
//double tenYearMonthlyPayment = loanPrinciple;
tenYearEditText.setText(String.valueOf(interestRate));
}
private void updateCustom(){
//customLengthTextView.setText(currentCustomLength + "year");
double customInterestRate = ((currentInterestRate/12) * .01);
int customLoanPrinciple = currentPurchaseAmount - currentDownPayment;
double customMonthlyPayment = customLoanPrinciple * customInterestRate /
(1-Math.pow(1+customInterestRate, -(currentCustomLength*12)));
customMonthlyEditText.setText(Double.toString(customMonthlyPayment));
}
#Override
protected void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putDouble(PURCHASE_AMOUNT, currentPurchaseAmount);
outState.putDouble(DOWN_PAYMENT, currentDownPayment);
outState.putDouble(INTEREST_RATE, currentInterestRate);
outState.putDouble(CUSTOM_LENGTH, currentCustomLength);
}
private OnSeekBarChangeListener customSeekBarListener = new OnSeekBarChangeListener(){
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
{
currentCustomLength = seekBar.getProgress();
updateCustom();
}
#Override
public void onStartTrackingTouch(SeekBar seekBar)
{
}
#Override
public void onStopTrackingTouch(SeekBar seekBar)
{
}
};
private TextWatcher textWatcher = new TextWatcher()
{
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
try
{
currentPurchaseAmount = Integer.parseInt(s.toString());
currentDownPayment = Integer.parseInt(s.toString());
currentInterestRate = Integer.parseInt(s.toString());
}
catch(NumberFormatException e)
{
currentPurchaseAmount = 0;
currentDownPayment = 0;
currentInterestRate = 0.0;
}
updateStandard();
updateCustom();
}
#Override
public void afterTextChanged(Editable s)
{
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
You're using a single TextWatcher for all three fields, and updating all three fields in the onTextChanged method.
I'm guessing that what you really want is three separate TextWatcher instances - one for each field, and to update only that one value in each one.
Is it possible to initialize all UI elements of certain type (like all TextViews or all LineraLayouts or ...) in a some kind of loop?
I have many layouts with a lot of the elements of the same type and it's really painful to do it all just by typing.
You can use RoboGuice .It doesn't use loops, but helps you to Inject your View, Resource, System Service, or any other object in to your code.
RoboGuice is a framework that brings the simplicity and ease of Dependency Injection to Android, using Google's own Guice library.
To give you an idea, take a look at this simple example of a typical Android activity:
class AndroidWay extends Activity {
TextView name;
ImageView thumbnail;
LocationManager loc;
Drawable icon;
String myName;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
name = (TextView) findViewById(R.id.name);
thumbnail = (ImageView) findViewById(R.id.thumbnail);
loc = (LocationManager) getSystemService(Activity.LOCATION_SERVICE);
icon = getResources().getDrawable(R.drawable.icon);
myName = getString(R.string.app_name);
name.setText( "Hello, " + myName );
}
}
This example is 19 lines of code. If you're trying to read through onCreate(), you have to skip over 5 lines of boilerplate initialization to find the only one that really matters: name.setText(). And complex activities can end up with a lot more of this sort of initialization code.
Compare this to the same app, written using RoboGuice:
class RoboWay extends RoboActivity {
#InjectView(R.id.name) TextView name;
#InjectView(R.id.thumbnail) ImageView thumbnail;
#InjectResource(R.drawable.icon) Drawable icon;
#InjectResource(R.string.app_name) String myName;
#Inject LocationManager loc;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
name.setText( "Hello, " + myName );
}
}
In this example, onCreate() is much easier to take in at a glance. All the platform boilerplate is stripped away and you're left with just your own app's business logic. Do you need a SystemService? Inject one. Do you need a View or Resource? Inject those, too, and RoboGuice will take care of the details.
RoboGuice's goal is to make your code be about your app, rather than be about all the initialization and lifecycle code you typically have to maintain in Android.
This text is from here
I have/had done something similar. Just for your reference, here's the code:
public class AbcActivity extends Activity
{
protected boolean changesPending;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.login_screen);
setViews(); //this method is created and called to take care of the buttons and edittext fields, and can probably hold a number of other fields/widgets as well
}
/** Take care of the Buttons and EditTexts here*/
private void setViews()
{
EditText userEdit = (EditText)findViewById(R.id.editText1);
EditText passwordEdit = (EditText)findViewById(R.id.editText2);
Button loginButton = (Button)findViewById(R.id.login_button);
loginButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
login(); // some random method
}
});
Button cancelButton = (Button)findViewById(R.id.cancel_button);
cancelButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
cancel(); //another random method
}
});
userEdit.addTextChangedListener(new TextWatcher()
{
public void onTextChanged(CharSequence s, int start, int before, int count)
{
changesPending = true;
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void afterTextChanged(Editable s) {}
});
passwordEdit.addTextChangedListener(new TextWatcher()
{
public void onTextChanged(CharSequence s, int start, int before, int count)
{
changesPending = true;
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void afterTextChanged(Editable s) {}
});
}
}
Hope this helps.
If you are trying to handle a large number of Views it may be worthwhile handling creation of these Views at runtime, attaching them to the relevant container. For example:
ViewGroup container = (ViewGroup) findViewById(R.id.container);
for(int i = 0; i < NUM_TEXT_VIEWS; i++){
TextView tv = new TextView(this); // where 'this' is your Activity
tv.setText("This is TextView " + i);
container.addView(tv);
}
Properties set in your xml file for a View usually have a corresponding Java method call.
In Android how can I make an EditText clear when it's clicked?
E.g., if I have an EditText with some characters in, such as 'Enter Name', when the user clicks on it these characters disappear.
I'm not sure if you are after this, but try this XML:
android:hint="Enter Name"
It displays that text when the input field is empty, selected or unselected.
Or if you want it to do exactly as you described, assign a onClickListener on the editText and set it empty with setText().
Are you looking for behavior similar to the x that shows up on the right side of text fields on an iphone that clears the text when tapped? It's called clearButtonMode there. Here is how to create that same functionality in an Android EditText view:
String value = "";//any text you are pre-filling in the EditText
final EditText et = new EditText(this);
et.setText(value);
final Drawable x = getResources().getDrawable(R.drawable.presence_offline);//your x image, this one from standard android images looks pretty good actually
x.setBounds(0, 0, x.getIntrinsicWidth(), x.getIntrinsicHeight());
et.setCompoundDrawables(null, null, value.equals("") ? null : x, null);
et.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (et.getCompoundDrawables()[2] == null) {
return false;
}
if (event.getAction() != MotionEvent.ACTION_UP) {
return false;
}
if (event.getX() > et.getWidth() - et.getPaddingRight() - x.getIntrinsicWidth()) {
et.setText("");
et.setCompoundDrawables(null, null, null, null);
}
return false;
}
});
et.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
et.setCompoundDrawables(null, null, et.getText().toString().equals("") ? null : x, null);
}
#Override
public void afterTextChanged(Editable arg0) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
});
after onclick of any action do below step
((EditText) findViewById(R.id.yoursXmlId)).setText("");
or
write this in XML file
<EditText
---------- other stuffs ------
android:hint="Enter Name" />
its works fine for me. Hope to you all.
that is called hint in android
use
android:hint="Enter Name"
#Harris's answer is great, I've implemented it as a separate subclass of EditText, which can make it easier to use if your code already adds TextChangedListeners.
Also, I've tweaked it so that, if you already use any Compound Drawables, it leaves them intact.
Code is here, for anyone who needs it:
package com.companyname.your
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
public class ClearableEditText extends EditText {
public String defaultValue = "";
final Drawable imgX = getResources().getDrawable(android.R.drawable.presence_offline ); // X image
public ClearableEditText(Context context) {
super(context);
init();
}
public ClearableEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public ClearableEditText(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
void init() {
// Set bounds of our X button
imgX.setBounds(0, 0, imgX.getIntrinsicWidth(), imgX.getIntrinsicHeight());
// There may be initial text in the field, so we may need to display the button
manageClearButton();
this.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
ClearableEditText et = ClearableEditText.this;
// Is there an X showing?
if (et.getCompoundDrawables()[2] == null) return false;
// Only do this for up touches
if (event.getAction() != MotionEvent.ACTION_UP) return false;
// Is touch on our clear button?
if (event.getX() > et.getWidth() - et.getPaddingRight() - imgX.getIntrinsicWidth()) {
et.setText("");
ClearableEditText.this.removeClearButton();
}
return false;
}
});
this.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
ClearableEditText.this.manageClearButton();
}
#Override
public void afterTextChanged(Editable arg0) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
});
}
void manageClearButton() {
if (this.getText().toString().equals("") )
removeClearButton();
else
addClearButton();
}
void addClearButton() {
this.setCompoundDrawables(this.getCompoundDrawables()[0],
this.getCompoundDrawables()[1],
imgX,
this.getCompoundDrawables()[3]);
}
void removeClearButton() {
this.setCompoundDrawables(this.getCompoundDrawables()[0],
this.getCompoundDrawables()[1],
null,
this.getCompoundDrawables()[3]);
}
}
If you want to have text in the edit text and remove it like you say, try:
final EditText text_box = (EditText) findViewById(R.id.input_box);
text_box.setOnFocusChangeListener(new OnFocusChangeListener()
{
#Override
public void onFocusChange(View v, boolean hasFocus)
{
if (hasFocus==true)
{
if (text_box.getText().toString().compareTo("Enter Text")==0)
{
text_box.setText("");
}
}
}
});
Be careful when setting text with an onClick listener on the field you are setting the text. I was doing this and setting the text to an empty string. This was causing the pointer to come up to indicate where my cursor was, which will normally go away after a few seconds. When I did not wait for it to go away before leaving my page causing finish() to be called, it would cause a memory leak and crash my app. Took me a while to figure out what was causing the crash on this one..
Anyway, I would recommend using selectAll() in your on click listener rather than setText() if you can. This way, once the text is selected, the user can start typing and all of the previous text will be cleared.
pic of the suspect pointer: http://i.stack.imgur.com/juJnt.png
//To clear When Clear Button is Clicked
firstName = (EditText) findViewById(R.id.firstName);
clear = (Button) findViewById(R.id.clearsearchSubmit);
clear.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.clearsearchSubmit);
firstName.setText("");
}
});
This will help to clear the wrong keywords that you have typed in so instead of pressing backspace again and again you can simply click the button to clear everything.It Worked For me. Hope It Helps
Code for clearing up the text field when clicked
<EditText android:onClick="TextFieldClicked"/>
public void TextFieldClicked(View view){
if(view.getId()==R.id.editText1);
text.setText("");
}
For me the easiest way...
Create an public EditText, for Example "myEditText1"
public EditText myEditText1;
Then, connect it with the EditText which should get cleared
myEditText1 = (EditText) findViewById(R.id.numberfield);
After that, create an void which reacts to an click to the EditText an let it clear the Text inside it when its Focused, for Example
#OnClick(R.id.numberfield)
void textGone(){
if (myEditText1.isFocused()){
myEditText1.setText("");
}
}
Hope i could help you, Have a nice Day everyone
((EditText) findViewById(R.id.User)).setText("");
((EditText) findViewById(R.id.Password)).setText("");
For kotlin's friends:
edtxt1.onFocusChangeListener = OnFocusChangeListener { _, hasFocus ->
if (hasFocus) {
edtxt1.text = ""
}
}