I recently have started to practice pure android apps , and now I am going to show how to register onclick events of controls in two ways. First way is our old java way , to associate separate onclick listener to each control like this :
btn_1.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
input_screen.append("0");
}
});
which is good but not best way.
Second way is to define your onClick method in the current context ( class ) and while handling the onClick events just give "this" ( context ) to the setOnClickListener method of controls and apply cases inside your onClick method, like given below :
btn_num_0.setOnClickListener(this);
btn_num_1.setOnClickListener(this);
public void onClick(View v) {
// TODO Auto-generated method stub
final int id = v.getId();
switch (id) {
case R.id.btn_num_0:
// your logic here
break;
case R.id.btn_num_1:
// your logic here
break;
// even more buttons here
}
}
So these are the two ways for registering events for controls.
btn_1.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
input_screen.append("0");
}
});
which is good but not best way.
Second way is to define your onClick method in the current context ( class ) and while handling the onClick events just give "this" ( context ) to the setOnClickListener method of controls and apply cases inside your onClick method, like given below :
btn_num_0.setOnClickListener(this);
btn_num_1.setOnClickListener(this);
public void onClick(View v) {
// TODO Auto-generated method stub
final int id = v.getId();
switch (id) {
case R.id.btn_num_0:
// your logic here
break;
case R.id.btn_num_1:
// your logic here
break;
// even more buttons here
}
}
So these are the two ways for registering events for controls.
No comments:
Post a Comment