Button
Button is a view , which perform actions when we clicked or pressed. Button represent a push-button widget , which invoke when user pressed or click that Button .
When you want work on a Button you need to follow these steps :
1. Define the Button resource
2.Assign the resource Id of that Button
3.Implement method
4. Run the application
Typical use of button in android application
public class MyActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = (Button) findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//statements to perform task on button click
}
});
}
}
1. Create a project in eclipse as android application
![]() |
| Create a Project |
2. Now Drag and drop the Button widget in activity_main.xml
activity_main.xml file :
3.MainActivity.java
Now write the code to provide the functionality on the click event.
File: MainActivity.java
3.MainActivity.java
Go to src folder and open MainActivity.java and Put the following code into that java file :
package com.example.buttonui;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn ;
btn=(Button) findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "I am Click", Toast.LENGTH_LONG).show();
}
});
}
}
3. Run the Application as Android Application on your Emulator or on device.
Explanation
1. Button btn ;
This line of code create the button object which you are going to use into your application.
2. btn.(Button)findViewById(R.id.button1);
This line Demonstrate that btn is a Button type object and button1 is the id by which btn is going to used in our application.
3.btn.setOnclickListner(new View.onClickListener(){
public void onClick(View v)
{
here you can put your code which is going to perform when click
event occur
}
);
4. View.onClickListener
Interface definition for callback to perform some action when user clicked that view.





0 comments:
Post a Comment