我是android的新手,请帮我解决这个问题。
当用户点击音量增加按钮时,我需要更新我的Android应用程序的TextView,每当用户点击按钮时,计数必须增加,如1,2,3,4,5 ...... 为此我做了如下
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
int action = event.getAction();
int keyCode = event.getKeyCode();
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
if (action == KeyEvent.ACTION_DOWN) {
int current = Integer.parseInt((String)counter_view.getText());
counter_view.setText(current+1+"");
}
return true;
default:
return super.dispatchKeyEvent(event);
}
}
此代码正常运行,但问题是textview更新速度非常慢,如果我连续按下按钮,那么更新textview只需要很少时间。还有其他方法可以做到这一点吗?
答案 0 :(得分:0)
尝试在runOnUiThread()中更新textview:
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_VOLUME_UP:
if (event.getAction() == KeyEvent.ACTION_DOWN) {
runOnUiThread(new Runnable() {
@Override
public void run() {
int current = Integer.parseInt((String)counter_view.getText());
counter_view.setText(current+1+"");
}
});
}
return true;
default:
return super.dispatchKeyEvent(event);
}
}
答案 1 :(得分:0)
尝试类似:
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
int action = event.getAction();
int keyCode = event.getKeyCode();
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
if (action == KeyEvent.ACTION_UP) {
runOnUiThread(new Runnable() {
@Override
public void run() {
int current = Integer.parseInt((String) counter_view.getText());
counter_view.setText(current + 1);
}
});
}
return true;
default:
return super.dispatchKeyEvent(event);
}
}
}
答案 2 :(得分:0)
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if(KEYCODE_VOLUME_UP==keyCode)
{
//do what you want to do here
return true;
}
return super.onKeyDown(keyCode, event);
}
在此过程中,您的关键事件将被非常快速地检测到,您也可以快速更改文本框值。 只需在KEYCODE_VOLUME_UP中输入音量调高键代码,这样每次按下该键时,文本框值都不会改变,而且您的音量应用功能在那时无法正常工作,因为我们返回true 而不是父类事件。