Android Development Linking Xml Button To Java
I am new to android development, I am basically trying to create a very basic app which will enable the user to switch on their wifi. My XML file:
Solution 1:
There are several ways of doing this.
then change the parameter of that function to
publicvoidgetWifiOn(View v){
return wifi_on;
}
with this you don't need the onClick
or any listeners
2.You can do something similar if you want all Buttons
to share the same function then give them all the function name like
android:onClick="someFunction"
then in Java do something like
publicvoidsomeFunction(View v)
{
Buttonbtn= (Button)v;
switch (v.getId())
{
case (R.id.wifi_on:
setWifiOn(btn);
break;
case (R.id.differentBtnId):
// do some other thingsbreak;
}
}
}
3.Less attractive in many situations, IMHO
publicclassMainActivityextendsActivityimplementsOnClickListener {
@OverrideprotectedvoidonCreate(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
}
@OverridepublicbooleanonCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);
returntrue;
}
@OverridepublicvoidonClick(View v) {
// TODO Auto-generated method stub
}
Note number 3 is the only one in which you need implements OnClickListener
I left out the other way because I think its the ugliest if you have more than one Button
Post a Comment for "Android Development Linking Xml Button To Java"