检测按下了哪个按钮 [英] Detect which button was pressed
问题描述
这是我的情况: 我以编程方式为某些按钮提供了onClickListener,但是,我无法完全处理此事件,因为我想检测按下了哪个按钮以赋予该按钮(当被按下时)一个新值.这是我对这些按钮进行编程的方式:
Here's my situation: I programmatically give some buttons an onClickListener, however, I can't fully-handle this event, because I'd like to detect which button was pressed to give to that button (when it is pressed) a new value. Here's how I program those buttons:
final View.OnClickListener soundButtonListener = new View.OnClickListener() {
public void onClick(View v) {
playSound(1);
int x = songPlay * songProgress;
mplayer.seekTo(x);
}
};
tableLayout = (TableLayout)v
.findViewById(R.id.tableLayout);
int number = 1;
for (int i = 0; i < tableLayout.getChildCount(); i++) {
TableRow row = (TableRow)tableLayout.getChildAt(i);
for (int j = 0; j < row.getChildCount(); j++) {
Button button = (Button) row.getChildAt(j);
button.setText("" + number);
button.setOnClickListener(soundButtonListener);
songProgress = j;
number++;
}
}
如您所见,它们并没有为每个听众提供点击监听器,因此当我按我的按钮时,mplayer始终会搜索到一点,因为songProgress停在64(我需要处理64个按钮).好的是,每个按钮都有一个数字(如您所看到的button.setText(" + number);),我想检查一下它们的编号以赋予songProgress不同的值.
As you see, they haven't a click listener for each one, so when I press my button, mplayer always seekto a point, becausae songProgress stops at 64 (I have 64 buttons to handle). What is good is that I have a number for each button (as you see button.setText("" + number);), and I'd like to check what is their number to give to songProgress different values.
推荐答案
如果我正确理解,您可以执行以下操作:
If i correctly understand you can do something like this:
final View.OnClickListener soundButtonOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if(v instanceof Button) {
Button button = (Button) v;
String text = button.getText().toString();
if(text == "1") {
//...
} else if(text == "2") {
}
//OR
switch (text) {
case "1": {
break;
}
case "2": {
break;
}
//...
}
}
}
};
但是我认为最好使用标签代替文本:
But in my opinion better use tag instead of text:
//set tag for your button
button.setTag(number);
//use this tag
Integer number = (Integer) v.getTag();
if(number != null) {
//...
}
这篇关于检测按下了哪个按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!