Wednesday, 28 August 2013

how to implement a button click in android

now let see simple and easy way to implement button click in android to start with it create new android project what we need first is a button in our xml file just drag a button though graphical view or you can add button code in xml view too

xml will look something like this


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/allahlogo"
    android:gravity="center"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />
 
   

</LinearLayout>


examine button code the first attribute says android:id we will be using it to call button in our src folder asking button to do something when it is clicked till now we kept a button on android screen but it should do should be coded in src folder with java


first in oncreate method call button refrences by following code

Button btnPlay = (Button) findViewById(R.id.btnPlay);

above code says btnplay is Button type which is refranced in xml file

now we need to implement listner on this button it can be done with this following code in java

btnplay.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(https://www.google.com")));

}
       
        });
       above code says whenever button btnplay is clicked startactivity with a intent with following url that is above code opens a browser with google.com site.. have a nice day and happy coding

No comments:

Post a Comment