ภาพรวม
ตัวอย่างนี้สาธิตวิธีการเพิ่มโฟกัสให้กับ WebView ในแอปพลิเคชัน Android เพื่อให้ผู้ใช้สามารถโต้ตอบกับเนื้อหาเว็บได้ทันทีเมื่อเปิดแอป
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
เปิด Android Studio ไปที่ File → New Project กรอกข้อมูลที่จำเป็นทั้งหมดเพื่อสร้างโปรเจกต์ใหม่
ขั้นตอนที่ 2: จัดทำ Layout (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">
<WebView
android:id="@+id/web_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
ในโค้ดข้างต้น เราใช้ WebView เพื่อแสดงเว็บไซต์ google.com
ขั้นตอนที่ 3: เขียนโค้ดหลัก (src/MainActivity.java)
package com.example.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebView;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
@RequiresApi(api = Build.VERSION_CODES.P)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView web_view = findViewById(R.id.web_view);
web_view.loadUrl("https://www.google.com/");
// เพิ่มโฟกัสให้ WebView
web_view.requestFocus();
// เปิดใช้งานการสัมผัสเบาๆ
web_view.getSettings().setLightTouchEnabled(true);
}
}
คำอธิบายสำคัญ:
requestFocus()- ขอโฟกัสให้ WebView เพื่อรับการป้อนข้อมูลจากผู้ใช้setLightTouchEnabled(true)- เปิดใช้งานการสัมผัสเบาๆ เพื่อปรับปรุงประสบการณ์การใช้งาน
ขั้นตอนที่ 4: กำหนดสิทธิ์ใน AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.myapplication">
<uses-permission android:name="android.permission.INTERNET"/>
<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 จริงกับคอมพิวเตอร์ ใน Android Studio เปิดไฟล์ Activity แล้วคลิกไอคอน Run จากแถบเครื่องมือ เลือกอุปกรณ์มือถือของคุณ แล้วตรวจสอบหน้าจอ - จะแสดงเว็บไซต์ Google พร้อมโฟกัสที่พร้อมใช้งาน
