Reputation: 1283
i want to fill the TextView with character while Button is Down i wrote this code but it just writes one character ?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button b = (Button) findViewById(R.id.btn);
final TextView tv =(TextView) findViewById(R.id.txt1);
b.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN){
String s = tv.getText().toString();
tv.setText( s + "E");
return false;
}
return false;
}
});
}
how can i fill the textview with a character while button state is down ?
Upvotes: 1
Views: 118
Reputation: 662
You can start a looping thread that populates your TextView
when you receive the MotionEvent.ACTION_DOWN
event
You can then use MotionEvent.ACTION_UP
event to stop that thread from running
Inside your thread you will need to invoke back to the UI thread before you will be able to modify the text inside the TextView
Upvotes: 1
Reputation: 15515
Okay.. Here is the solution. Tried using Handler
.
Button b = (Button) findViewById(R.id.btn);
final TextView tv = (TextView) findViewById(R.id.txt1);
b.setOnTouchListener(new OnTouchListener() {
private Handler mHandler;
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (mHandler != null)
return true;
mHandler = new Handler();
mHandler.postDelayed(mAction, 500);
return false;
} else if (event.getAction() == MotionEvent.ACTION_UP) {
if (mHandler == null)
return true;
mHandler.removeCallbacks(mAction);
mHandler = null;
return false;
}
return false;
}
Runnable mAction = new Runnable() {
@Override
public void run() {
String s = tv.getText().toString();
tv.setText(s + "E");
mHandler.postDelayed(this, 500);
}
};
});
Reference. I hope this will help you.
Upvotes: 1
Reputation: 6928
You could do something like this:
Make a boolean member variable to use as a flag for filling the textview. In the on touch down set that boolean to true, and start a runnable which sets the text, and then starts another runnable. This creates a loop. In the on touch up, set the boolean to false, and the loop will stop. Something like this (untested):
private boolean mFillTextView = false;
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN){
mFillTextView = true;
Handler mHandler= new Handler();
mHandler.postDelayed(new MyRunnable(), 300);
return false;
}
if (event.getAction() == MotionEvent.ACTION_UP){
mFillTextView =false;
}
return false;
}
});
class MyRunnable implements Runnable{
@Override
public void run() {
if (mFillTextView){
mTextView.setText(mTextView.getText()+"a");
mHandler.postDelayed(new MyRunnable(), 300);
})};
}
Upvotes: 1