How do I clear the text in Android TextView?
Try this,
public class AndroidDemo extends Activity implements OnClickListener{
Button add, clear;
EditText text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
add = (Button) findViewById(R.id.addBtn);
clear = (Button) findViewById(R.id.clrBtn);
text = (EditText) findViewById(R.id.display);
add.setOnClickListener(this);
clear.setOnClickListener(this);
}
@Override
public void onClick(View v){
if(v == add){
text.setText(messages[new java.util.Random().nextInt(messages.length)]);
}else if(v == clear){
text.setText("");
}
}
}
Yes it is. Your problem is related to the onClickListener.
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(v == add){
text.setText(messages[new java.util.Random().nextInt(messages.length)]);
}else if(v == clear){
text.setText("");
}
}
});
in this case if(v == clear)
is always false. You have to register a View.OnClickListener()
for the clear
view/button, or make your Activity implements View.OnClickListener
and set for both the button this
as setOnClickListener
To answer your question, I use this method in my apps.
Instead of setting the text to ("")
, it clears the stored value using the getText().clear();
method. Personally, I use this because it looks more professional and makes proper use of the clear command in android.
clearButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
editText.getText().clear();
}
});
EDIT: The original post had the tag 'EditText', so I answered the question with that in mind.
This works with EditText, With a TextView, just call textview.setText("");