• Android Video Tutorials

Android - 拼寫檢查器



Android 平臺提供了一個拼寫檢查框架,允許您在應用程式中實現和訪問拼寫檢查功能。

為了使用拼寫檢查器,您需要實現`SpellCheckerSessionListener`介面並重寫其方法。其語法如下:

public class HelloSpellCheckerActivity extends Activity implements SpellCheckerSessionListener {
   @Override
   public void onGetSuggestions(final SuggestionsInfo[] arg0) {
      // TODO Auto-generated method stub
   }
   
   @Override
   public void onGetSentenceSuggestions(SentenceSuggestionsInfo[] arg0) {
      // TODO Auto-generated method stub
   }
}

接下來,您需要建立一個`SpellCheckerSession`類的物件。可以透過呼叫`TextServicesManager`類的`newSpellCheckerSession`方法來例項化此物件。此類處理應用程式和文字服務之間的互動。您需要請求系統服務來例項化它。其語法如下:

private SpellCheckerSession mScs;
final TextServicesManager tsm = (TextServicesManager) getSystemService(
Context.TEXT_SERVICES_MANAGER_SERVICE);
mScs = tsm.newSpellCheckerSession(null, null, this, true);   

最後,您需要呼叫`getSuggestions`方法來獲取任何您想要的文字的建議。建議將傳遞到`onGetSuggestions`方法,您可以從中執行任何操作。

mScs.getSuggestions(new TextInfo(editText1.getText().toString()), 3);

此方法接受兩個引數。第一個引數是以`TextInfo`物件形式的字串,第二個引數是用於區分建議的 cookie 編號。

除了這些方法外,`SpellCheckerSession`類還提供了其他方法來更好地處理建議。這些方法列在下面:

序號 方法及描述
1

cancel()

取消掛起的和正在執行的拼寫檢查任務

2

close()

完成此會話並允許 TextServicesManagerService 斷開繫結拼寫檢查器的連線

3

getSentenceSuggestions(TextInfo[] textInfos, int suggestionsLimit)

從指定的句子中獲取建議

4

getSpellChecker()

獲取此拼寫檢查會話擁有的拼寫檢查服務資訊。

5

isSessionDisconnected()

如果此會話的文字服務的連線已斷開並且沒有活動,則返回 true。

示例

這是一個演示拼寫檢查器用法的示例。它建立一個基本的拼寫檢查應用程式,允許您編寫文字並獲取建議。

要試用此示例,您可以在實際裝置或模擬器上執行它。

步驟 描述
1 您將使用 Android Studio 在包 com.example.sairamkrishna.myapplication 下建立一個 Android 應用程式。
2 修改 src/MainActivity.java 檔案以新增必要的程式碼。
3 修改 res/layout/main 檔案以新增相應的 XML 元件
4 執行應用程式,選擇正在執行的 Android 裝置,將應用程式安裝到該裝置上並驗證結果

以下是修改後的主活動檔案 `src/MainActivity.java` 的內容。

package com.example.sairamkrishna.myapplication;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.textservice.TextInfo;
import android.view.textservice.TextServicesManager;

import android.widget.Button;
import android.widget.EditText;

import android.view.textservice.SentenceSuggestionsInfo;
import android.view.textservice.SpellCheckerSession;
import android.view.textservice.SpellCheckerSession.SpellCheckerSessionListener;
import android.view.textservice.SuggestionsInfo;

import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements SpellCheckerSessionListener  {
   Button b1;
   TextView tv1;
   EditText ed1;
   private SpellCheckerSession mScs;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      b1=(Button)findViewById(R.id.button);
      tv1=(TextView)findViewById(R.id.textView3);

      ed1=(EditText)findViewById(R.id.editText);
      b1.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            Toast.makeText(getApplicationContext(),
               ed1.getText().toString(),Toast.LENGTH_SHORT).show();
            mScs.getSuggestions(new TextInfo(ed1.getText().toString()), 3);
         }
      });
   }

   public void onResume() {
      super.onResume();
      final TextServicesManager tsm = (TextServicesManager)
         getSystemService(Context.TEXT_SERVICES_MANAGER_SERVICE);
      mScs = tsm.newSpellCheckerSession(null, null, this, true);
   }

   public void onPause() {
      super.onPause();
      if (mScs != null) {
         mScs.close();
      }
   }

   public void onGetSuggestions(final SuggestionsInfo[] arg0) {
      final StringBuilder sb = new StringBuilder();

      for (int i = 0; i < arg0.length; ++i) {
         // Returned suggestions are contained in SuggestionsInfo
         final int len = arg0[i].getSuggestionsCount();
         sb.append('\n');

         for (int j = 0; j < len; ++j) {
            sb.append("," + arg0[i].getSuggestionAt(j));
         }

         sb.append(" (" + len + ")");
      }
		
      runOnUiThread(new Runnable() {
         public void run() {
            tv1.append(sb.toString());
         }
      });
   }

   @Override
   public void onGetSentenceSuggestions(SentenceSuggestionsInfo[] arg0) {
      // TODO Auto-generated method stub
   }
}

以下是修改後的 xml 檔案 `res/layout/main.xml` 的內容。

在下面的程式碼中,`abc` 表示 tutorialspoint.com 的徽標
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
   android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
   
   <TextView android:text="Spell checker " android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/textview"
      android:textSize="35dp"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true" />
      
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials point"
      android:id="@+id/textView"
      android:layout_below="@+id/textview"
      android:layout_centerHorizontal="true"
      android:textColor="#ff7aff24"
      android:textSize="35dp" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Suggestions"
      android:id="@+id/button"
      android:layout_alignParentBottom="true"
      android:layout_centerHorizontal="true" />
      
   <EditText
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/editText"
      android:hint="Enter Text"
      android:layout_above="@+id/button"
      android:layout_marginBottom="56dp"
      android:focusable="true"
      android:textColorHighlight="#ff7eff15"
      android:textColorHint="#ffff25e6"
      android:layout_alignRight="@+id/textview"
      android:layout_alignEnd="@+id/textview"
      android:layout_alignLeft="@+id/textview"
      android:layout_alignStart="@+id/textview" />
      
   <ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageView"
      android:src="@drawable/abc"
      android:layout_below="@+id/textView"
      android:layout_centerHorizontal="true" />
      
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Suggestions"
      android:id="@+id/textView3"
      android:textSize="25sp"
      android:layout_below="@+id/imageView" />

</RelativeLayout>

以下是 `res/values/string.xml` 檔案的內容。

<resources>
   <string name="app_name">My Application</string>
</resources>

以下是 `AndroidManifest.xml` 檔案的內容。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.sairamkrishna.myapplication" >
   
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      
      <activity
         android:name=".MainActivity"
         android:label="@string/app_name" >
         
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
         
      </activity>
      
   </application>
</manifest>

讓我們嘗試執行我們剛剛修改的應用程式。我假設您在進行環境設定時已經建立了您的 AVD。要從 Android Studio 執行應用程式,請開啟專案中的一個活動檔案,然後單擊工具欄中的執行 Eclipse Run Icon 圖示。Android Studio 將應用程式安裝到您的 AVD 並啟動它,如果您的設定和應用程式一切正常,它將顯示以下模擬器視窗:

Android Spell Checker Tutorial

現在您需要做的就是在欄位中輸入任何文字。例如,我已經輸入了一些文字。按下建議按鈕。以下通知將與建議一起出現在您的 AVD 中:

Android Spell Checker Tutorial

現在更改文字並再次按下按鈕,就像我做的那樣。這就是螢幕上顯示的內容。

Android Spell Checker Tutorial
廣告