有几种方法可以做到这一点。
- 您可以做的就是将此行添加到
<Button
xml中的标签中
android:onClick="setWifiOn"
然后将该函数的参数更改为
public void getWifiOn(View v){return wifi_on;}这样,您就不需要
onClick或任何听众
2.如果您想让所有人
Buttons共享相同的功能,然后给他们所有的功能名称,例如
android:onClick="someFunction"
然后在Java中执行类似
public void someFunction(View v){ Button btn = (Button)v; switch (v.getId()) { case (R.id.wifi_on: setWifiOn(btn); break; case (R.id.differentBtnId): // do some other things break; }}}3.恕我直言,在很多情况下吸引力都较小
public class MainActivity extends Activity implements onClickListener { @Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button wifiBtn = (Button) findViewById(R.id.wifi_on); wifiBtn.setonClickListener(this); // your onClick below will be called then you will still have to check the id of the Button // multiple buttons can set the same listener and use a switch like above}@Overridepublic boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true;}@Overridepublic void onClick(View v) { // TODO Auto-generated method stub}笔记 编号3是您唯一需要的一个
implements OnClickListener
按钮文档
我省略了另一种方式,因为如果您有多个,我认为这是最丑的
Button



