परिचय
यह उदाहरण दर्शाता है कि जब Android में EditText फोकस प्राप्त करे तो सॉफ्ट कीबोर्ड प्रोग्रामेटिक रूप से कैसे दिखाया जाए।
चरण 1: नया प्रोजेक्ट बनाएं
Android Studio में File → New Project चुनकर एक नया प्रोजेक्ट बनाएं।
चरण 2: लेआउट XML में EditText जोड़ें
res/layout/activity_main.xml में निम्नलिखित कोड जोड़ें:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>
चरण 3: MainActivity.java में कीबोर्ड लॉजिक लागू करें
src/MainActivity.java में निम्नलिखित कोड जोड़ें:
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;
public class MainActivity extends AppCompatActivity {
EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.editText);
showSoftKeyboard(editText);
}
public void showSoftKeyboard(View view) {
if (view.requestFocus()) {
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
}
}
}
चरण 4: AndroidManifest.xml कॉन्फ़िगर करें
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
ऐप चलाएं
डिवाइस कनेक्ट करें, Android Studio से ऐप चलाएं, और EditText फोकस प्राप्त करते ही कीबोर्ड स्वचालित रूप से दिखाई देगा।
