Android Tutorial OnClickListener

So far in this android tutorial we have used the android:onClick attribute in the xml for the actions that should be performed when we click on the button. There is another alternative to the android:onClick attribute which is the OnClickListener. Android onclicklistener is used on Android views  like buttons,textviews,edittexts etc.
In this tutorial we will use android OnClickListener on button. When the button is clicked it displays a message "button is clicked".

here is the XML code
<?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
 xmlns:app="http://schemas.android.com/apk/res-auto" 
 xmlns:tools="http://schemas.android.com/tools" 
 android:layout_width="match_parent" 
 android:layout_height="match_parent" 
 android:paddingBottom="@dimen/activity_vertical_margin" 
 android:paddingLeft="@dimen/activity_horizontal_margin" 
 android:paddingRight="@dimen/activity_horizontal_margin" 
 android:paddingTop="@dimen/activity_vertical_margin" 
 app:layout_behavior="@string/appbar_scrolling_view_behavior" 
 tools:showIn="@layout/activity_main">


    <Button 
 style="?android:attr/buttonStyleSmall" 
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content" 
 android:text="Button" 
 android:id="@+id/button" 
 android:layout_marginTop="187dp" 
 android:layout_alignParentTop="true" 
 android:layout_centerHorizontal="true" />


</RelativeLayout>
 
Java Code
 
public class MainActivity extends AppCompatActivity {



    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button)findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // the actions to be performed when the button is clicked                Toast.makeText(MainActivity.this,"Button is clicked",Toast.LENGTH_SHORT).show();
            }
        });
    }
}
 
The actions which you want to perform when the  button is clicked goes inside the onClick()
method.
 
onclicklistener
 
 

0 comments: