[英]Android Java, setOnTouchListener delete 1 last character from string every 0.25s
I am making calculator on java.我正在用java制作计算器。 I want to make a button, which corresponds to delete the last character.
我想做一个按钮,对应删除最后一个字符。
If you press on it for 1 second, it starts to delete 1 character every 0.25s form EditText string.如果你按住它 1 秒,它开始每 0.25 秒从 EditText 字符串中删除 1 个字符。
Clear button:清除按钮:
clear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(operation.length() != 0){
String s=operation.getText().toString();
s = s.substring(0,operation.length()-1);
operation.setText(s);}
}
});
Long touch idea:长触理念:
clear.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
});
You can use ScheduledExecutorService to schedule Runnables at a set rate and with an initial delay.您可以使用 ScheduledExecutorService 以设定的速率和初始延迟调度 Runnable。 Here's how I would do it:
这是我将如何做到的:
// Create member variables for your ExecutorService and ScheduledFuture
private ScheduledExecutorService mExecutor;
private ScheduledFuture<?> mFuture;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
final EditText editText = findViewById(R.id.textView);
final Button button = findViewById(R.id.button2);
// Set up the ExecutorService
mExecutor = Executors.newSingleThreadScheduledExecutor();
final Runnable deleteRunnable = new Runnable() {
@Override
public void run() {
// We'll use the view's post() method
// to make sure we're updating it from the correct thread
editText.post(new Runnable() {
@Override
public void run() {
String textValue = editText.getText().toString();
if(textValue.length() > 0){
// Delete the last character
textValue = textValue.substring(0, textValue.length() - 1);
Log.d("MY_LOG_TAG", textValue);
editText.setText(textValue);
}
// (Optionally)
// Keep the cursor at the end of the text
editText.setSelection(textValue.length());
}
});
}
};
button.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch(action){
case MotionEvent.ACTION_DOWN:
Log.d("MY_LOG_TAG", "Action down");
// Schedule the runnable with an initial delay of 1000 milliseconds
// and at a rate of 250 milliseconds
mFuture = mExecutor.scheduleAtFixedRate(deleteRunnable, 1000, 250, TimeUnit.MILLISECONDS);
break;
case MotionEvent.ACTION_UP:
Log.d("MY_LOG_TAG", "Action up");
// Cancel the scheduled runnable when the Up event is triggered
if(mFuture != null){
mFuture.cancel(false);
}
break;
}
return false;
}
});
}
@Override
protected void onDestroy() {
// Shutdown the Executor Service
mExecutor.shutdown();
super.onDestroy();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.