在android app中为所有按钮点击事件的常用方法编码,这里是代码,
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.filter);
btnOne = (Button)findViewById(R.id.btnone);
btnTwo = (Button)findViewById(R.id.btntwo);
btnThree = (Button)findViewById(R.id.btnthree);
btnFour = (Button)findViewById(R.id.btnfour);
btnFive = (Button)findViewById(R.id.btnfive);
btnSix = (Button)findViewById(R.id.btnsix);
btnSeven = (Button)findViewById(R.id.btnseven);
btnEight = (Button)findViewById(R.id.btneight);
btnNine = (Button)findViewById(R.id.btnnine);
btnTen = (Button)findViewById(R.id.btnten);
OnClickListener listener = new OnClickListener()
{
public void onClick(View v) {
// TODO Auto-generated method stub
doAction(v);
}
};
}
public void doAction(View v)
{
Object tagObject = v.getTag();
int tag = (Integer) v.getTag();
String val = (String) d.get(tag);
if(val.equals("off"))
{
//select(tagObject);
//d.put(tag, "on");
Toast.makeText(getBaseContext(), "Button"+tag+"select", Toast.LENGTH_LONG).show();
}
else if(val.equals("on"))
{
//unSelect(tagObject);
//d.put(tag, "off");
Toast.makeText(getBaseContext(), "Button"+tag+"unselect", Toast.LENGTH_LONG).show();
}
}
此代码对我不起作用。请提出任何想法.......提前致谢
答案 0 :(得分:2)
如何首先声明您的侦听器,然后在您的观看中调用setOnClickListener
:
OnClickListener listener = new OnClickListener()
{
public void onClick(View v) {
// TODO Auto-generated method stub
doAction(v);
}
};
btnOne.setOnClickListener(listener);
btnTwo.setOnClickListener(listener);
...
答案 1 :(得分:1)
您已声明了侦听器,但忘记为每个按钮设置侦听器。
对所有按钮执行此操作:btnOne.setOnClickListener(listener);
答案 2 :(得分:0)
您需要在按钮中设置监听器..
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.filter);
...
OnClickListener listener = new OnClickListener()
{
public void onClick(View v) {
// TODO Auto-generated method stub
doAction(v);
}
};
btnOne.setOnClickListener();
btnTwo = (Button)findViewById(R.id.btntwo);
...
}
答案 3 :(得分:0)
让您的班级实施View.OnClickListener
,例如
public class MyActivity extends Activity implements View.OnClickListener {
Button button1, button2, button3;
@Override
public void onCreate(Bundle bundle) {
super.onCreate();
...
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.button1:
// do stuff;
break;
case R.id.button2:
// do stuff;
break;
...
}
}