2012-12-03 104 views
-1

在Android應用程序編碼爲常用的方法對所有按鈕點擊事件,這裏是代碼,如何爲按鈕單擊事件聲明公共監聽器?

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(); 
    } 
} 

此代碼是不是爲我工作。請給任何想法.......在此先感謝

回答

2

如何首先宣佈你的聽衆,然後調用您的看法setOnClickListener

OnClickListener listener = new OnClickListener() 
{ 

    public void onClick(View v) { 
     // TODO Auto-generated method stub 
     doAction(v); 
    } 

}; 
btnOne.setOnClickListener(listener); 
btnTwo.setOnClickListener(listener); 
... 
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); 
    ... 

} 
1

您已聲明偵聽器,但忘記爲每個按鈕設置偵聽器。 這樣做對所有的按鈕:btnOne.setOnClickListener(listener);

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; 
     ... 
    } 
}