March 25, 2016

In this tutorial I’m going to show you how to show a toast in Kotlin Language. Previously in Android while doing so, we will implement OnClickListener and then we will provide a method. But on the other hand in Kotlin its just a one line. In my previous tutorial I had explained the features of Kotlin language, about Extensive Functions. With this feature it is a single line coding on showing you the Toast.

Previously in Android:

  Button _buttonToast;  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_toast);  
        _buttonToast = (Button) findViewById(R.id.buttonToast);  
        _buttonToast.setOnClickListener(new View.OnClickListener() {  
            @Override  
            public void onClick(View v) {  
                Toast.makeText(getApplicationContext(), "Showing Toast", Toast.LENGTH_SHORT).show();  
            }  
        });  
    }  

Now in Kotlin:

 internal var _button: Button? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        _button = findViewById(R.id.button) as Button?
        _button?.setOnClickListener { Toast.makeText(applicationContext, "You Clicked", Toast.LENGTH_LONG).show() }
    }

Its pretty easy to do in Kotlin and its fast too.