This is linked to a previous post:
My layout is like this:
INPUT TEXT (EditText)
BUTTON
OUTPUT TEXT (TextView)
Task:
When the user enters an input & upon button click the output text appears.
I have to make sure I make the input & output disappear some 10 seconds after the button click(and after the output text appears).
Now, I cannot add a “TextWatcher” on TextView.
Initially I tried to use Handler on inputText which can have a TextWatcher. But somehow the Handler keeps running all the time in the background & I cannot “cancel” it.
So I switched to using timers. I used a method in the button onCick() method:
onClick(){... eraseText();....}public void eraseText(){TimerTask task = new TimerTask() { public void run() { inputText.setText(""); outputText.setText(""); } }; Timer timer = new Timer(); timer.schedule(task, 1000,10000);}
And after 10 seconds I would like to call timer.cancel() ( yet don’t know where!!)
As you can see the problem is that I obtain an error complaining that only UI threads can alter views. How can do this ?
Thanks
I would use Handler class. You can easily post delayed code & cancel it. It will run in correct Thread. Also, you can add TextWatcher or OnFocusChangeListener to detect & cancel text erasing when a user starts editing text again.
Handler handler;@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); handler = new Handler(); final TextView textView = (TextView) findViewById(R.id.textView2); final EditText editText = (EditText) findViewById(R.id.editText1); final Runnable eraseText = new Runnable() { @Override public void run() { textView.setText(""); editText.setText(""); } }; editText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { handler.removeCallbacks(eraseText); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub } }); editText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View arg0, boolean arg1) { handler.removeCallbacks(eraseText); } }); findViewById(R.id.button1).setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { textView.setText(editText.getText().toString()); handler.removeCallbacks(eraseText); handler.postDelayed(eraseText, 1000); } });}
No comments:
Post a Comment