activity_main.xmlMainActivity.java
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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:orientation="vertical" android:padding="16dp" tools:context="com.codinginflow.closekeyboardexample.MainActivity"> <TextView android:id="@+id/text_view_result" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="Hello World!" android:textSize="20sp" /> <EditText android:id="@+id/edit_text_input" android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:onClick="setText" android:text="Set Text" /> </LinearLayout>
package com.codinginflow.closekeyboardexample; import android.content.Context; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private TextView textViewResult; private EditText editTextInput; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textViewResult = findViewById(R.id.text_view_result); editTextInput = findViewById(R.id.edit_text_input); } public void setText(View v) { String newText = editTextInput.getText().toString(); textViewResult.setText(newText); closeKeyboard(); } private void closeKeyboard() { View view = this.getCurrentFocus(); if (view != null) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0); } } }