0

I always found one problem whenever i make forms (for example, login or registration form) in my applications, that problem is hiding keyboard when user clicks on submit button. For solving this problem i always write keyboard hiding code in the very 1st line in the click listener, this solution was fine if i've only 1 or 2 forms in my app, but if there are saveral forms in an app than it becomes a certain overhead on the actual business logic of the app. Taking this overhead of maintaining 'keyboard visibility' in mind i've developed a generic solution to handle this problem. I am learning to develop android app using kotlin and by using 'default methods' of interface of kotlin i've developed this code.

I am sharing the code with you and i need your suggestions and improvements on this approach.

I want to know whether i can use this approach in my live projects or i just can't use this approach because this is wrong. Please give me your valuable feedback.

MainActivity :

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity(), CustomOnClickListener {

    override fun onClick(v: View?) {
        super<CustomOnClickListener>.onClick(v)
        when(v?.id){
            R.id.button1 -> Toast.makeText(this, "button1 clicked", Toast.LENGTH_LONG).show()
            R.id.button2 -> Toast.makeText(this, "button2 clicked", Toast.LENGTH_LONG).show()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        button1.setOnClickListener(this)
        button2.setOnClickListener(this)
    }
}

CustomOnClickListener

import android.app.Activity
import android.content.Context
import android.view.View
import android.view.inputmethod.InputMethodManager

interface CustomOnClickListener : View.OnClickListener{
    override fun onClick(v: View?) {
        v?.hideKeyboard()
    }
}

fun View.hideKeyboard() {
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(windowToken, 0)
}
  • create base activity which will extend AppcompatActivity and put keyboard hiding method inside this, extend base activity where you want. this approach will reduce your code and remove boiler plate code this is called inheritance or reusability of code. – Hemant Parmar Mar 28 '19 at 07:01
  • @HemantParmar, in my previous apps i've used your approch of making a base class for activity as well as fragments. But at that time i've to write methods (for hiding keyboard) in both BaseActivity as well as BaseFragment classes which was duplicating my code. But i've developed this solution to make it more generic and so that code duplication will be prevented. – Rahul Sonpaliya Mar 28 '19 at 07:13

0 Answers0