Ranjan Bajracharya
1 min readDec 8, 2017

Android Development — Part 4

OnClickListener vs onClick

These two methods have same purpose i.e to user can tap or click to perform an action.But way to implement it is a bit different. android:onClick was added in API level 4 to make it easier, more Javascript-web-like, and drive everything from the XML. What it does internally is add an OnClickListener on the Button, which calls your onClickButton method.

Implementing onCLick event:-

First you need to define in android:onClick="myListener" XML file.Such as in activity_main.xml

<Button
android:id="@+id/button_id"
android:layout_width="340dp"
android:layout_height="56dp"
android:layout_marginTop="8dp"
android:onClick="onClickButton"
android:text="OnClick"
/>

Then define onClickButton method in MainActivity.java.

public void onClickButton(View v){
//do stuffs
Toast.makeText(this, "This is onClick Event", Toast.LENGTH_SHORT).show();
}

Implementing OnClickListener event:-

For this define it inside onCreate() Activity

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//do stuffs
Toast.makeText(MainActivity.this, "This is OnClickListener", Toast.LENGTH_SHORT).show();
}
});
}

Toast

In both event inside the function Toast id define. A toast is a simple feedback about an operation in a small popup. It only fills the amount of space required for the message and the current activity remains visible and interactive. Toasts automatically disappear after a timeout.

Toast object looks like this

Toast.makeText(context, text, duration).show();

where

makeText() is a method, with three parameters the application Context, the text message, and the duration for the toast

show() displays toast notification.

Ranjan Bajracharya
Ranjan Bajracharya

Written by Ranjan Bajracharya

MSP 2017. Graduation in computer science and information technology. Studying MBA.

No responses yet