Wednesday, October 12, 2011

Remove Keyboard after click outside the EditText

For this you have to take the onTouchListener on the parent layout of the Layout File. on the TouchListener you have to code to hide the Keyboard when click outside the EditText. Please follow following XML Layout and Java class to resolve this issue.

keyboardmain.xml


xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:id="@+id/LinearLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/editText1">




MainActivity.java
package com.at.keyboardhide;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.at.bugsfixing.R;

public class MainActivity extends Activity implements OnTouchListener{
private EditText getEditText;
private LinearLayout getLinearLayout;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.keyboardmain);
getEditText = (EditText)findViewById(R.id.editText1);
getLinearLayout = (LinearLayout)findViewById(R.id.LinearLayout01);
getLinearLayout.setOnTouchListener(this);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
if(v==getLinearLayout){
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getEditText.getWindowToken(), 0);
return true;
}
return false;
}
}

5 comments:

  1. i am using absolute view in main.xml i created a new xml by keyboard name then it gives error to

    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/editText1">

    explain me in detail

    ReplyDelete
  2. The formatting kind of sucks but aside from that it works well. Thanks man.

    ReplyDelete
  3. Hurt my eyes while sorting though the formatting :D but THANKS, this helped a lot. :) Works like a charm. :)

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete