This post helps you to learner about listening to click events in android
1.Create two buttons using XML file under /res/layout
2.I named two buttons as sendBtn and cancelBtn
3.Make buttons to listen to click events by following code
public class CreateMessage extends Activity implements OnClickListener
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button sendBtn=(Button)findViewById(R.id.sendMsg);
sendBtn.setOnClickListener(this);
Button cancelBtn=(Button)findViewById(R.id.cancelMsg);
cancelBtn.setOnClickListener(this);
}
}
4.Using getId() find which button is clicked
public void onClick(View v)
{
Button clickedButton=(Button)v;
switch(clickedButton.getId())
{
case R.id.sendMsg:
Toast.makeText(this, "Message Sent",50).show(); //it displays a message
break;
case R.id.cancelMsg:
finish(); //it closes current activity
break;
default:
throw new RuntimeException("Unknow button ID");
}
}
NOTE: Include these header files import android.view.View;
import android.view.View.OnClickListener;
1.Create two buttons using XML file under /res/layout
2.I named two buttons as sendBtn and cancelBtn
3.Make buttons to listen to click events by following code
public class CreateMessage extends Activity implements OnClickListener
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button sendBtn=(Button)findViewById(R.id.sendMsg);
sendBtn.setOnClickListener(this);
Button cancelBtn=(Button)findViewById(R.id.cancelMsg);
cancelBtn.setOnClickListener(this);
}
}
4.Using getId() find which button is clicked
public void onClick(View v)
{
Button clickedButton=(Button)v;
switch(clickedButton.getId())
{
case R.id.sendMsg:
Toast.makeText(this, "Message Sent",50).show(); //it displays a message
break;
case R.id.cancelMsg:
finish(); //it closes current activity
break;
default:
throw new RuntimeException("Unknow button ID");
}
}
NOTE: Include these header files import android.view.View;
import android.view.View.OnClickListener;
No comments:
Post a Comment