Saturday 2 February 2013

How To use button In android

How To use Buttons Event
In this Section we see that how we use android Button widget in android application and how we hendal Button event.
Step 1: First create A new Project. Then in our activity layout Put a button  from widget controls. then our layout look like bellow code
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ButtonActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="29dp"
        android:text="Button" />

</RelativeLayout>

Setp 2: Now in java Code

import android.os.Bundle;
import android.app.Activity;
public class ButtonActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_button);
}
}


Create Object of Button and assing with button which is created in layout
Button b=(Button)findViewById(R.id.button1);
Now Set Click Event on Button Object

b.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
//write code which you want to do on click event
}
});

No comments:

Post a Comment