user2374527 user2374527 - 4 months ago 18
Java Question

How to clear the string in the editText when clicking on it

I really wish that you can help me. I my application in Android to clear or erase the the default string assigned to the editText object on the main Activity when clicking on it, only if the value is equal to this text "Enter a message here", which I assigned it in the R.java file as "R.string.editTextOnStart". Here's the code:

public class MainActivity extends AppCompatActivity {

private String text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

final TextView textView = (TextView) findViewById(R.id.textView);
final EditText editText = (EditText) findViewById(R.id.editText);

editText.setText(R.string.editTextOnStart);

textView.setText(R.string.textViewString);

//if(editText.getText().toString().equals(String.valueOf(R.string.editTextOnStart))) {

editText.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
text = editText.getText().toString();

if(text.equals(R.string.editTextOnStart)) {
editText.getText().clear();
}
}
});
//}
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
textView.setText(editText.getText().toString());
}
});
}
}

Answer

Instead of doing that, you can specify the following using hint

In your layout xml file , under your EditText, add this

android:hint="Enter your text here"

This will appear on your edit text when you start the activity and disappears when user have clicked on it

Comments