Android之離線詞典

來源:互聯網
上載者:User

1. 首先在res/raw中匯入檔案dictionary.db/Files/lee0oo0/dictionary.rar

2. main.xml檔案的布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <AutoCompleteTextView android:id="@+id/actvWord"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:layout_marginTop="10dp" android:singleLine="true" />
    <Button android:id="@+id/btnSelectWord" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:text="查單詞" />

3. AutoCompleteTextView的每個textview下拉布局

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tvWordItem"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:gravity="center_vertical"
    android:paddingLeft="6dip"
    android:textColor="#000"    
    android:minHeight="?android:attr/listPreferredItemHeight"/>  

 

4. 主程式,都幾乎帶有注釋

 package net.blogjava.mobile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.TextView;

public class Main extends Activity implements OnClickListener, TextWatcher
{
    //dictionary.db的儲存目錄
    private final String DATABASE_PATH = android.os.Environment
            .getExternalStorageDirectory().getAbsolutePath()
            + "/dictionary";
    private AutoCompleteTextView actvWord;
    private final String DATABASE_FILENAME = "dictionary.db";
    private SQLiteDatabase database;
    private Button btnSelectWord;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);
        //開啟Database
        database = openDatabase();
        btnSelectWord = (Button) findViewById(R.id.btnSelectWord);
        actvWord = (AutoCompleteTextView) findViewById(R.id.actvWord);
        //設定按鈕監聽
        btnSelectWord.setOnClickListener(this);
        //設施字元改變監聽
        actvWord.addTextChangedListener(this);
    }

    public class DictionaryAdapter extends CursorAdapter
    {
        private LayoutInflater layoutInflater;
        @Override
        public CharSequence convertToString(Cursor cursor)
        {
            return cursor == null ? "" : cursor.getString(cursor
                    .getColumnIndex("_id"));
        }

        private void setView(View view, Cursor cursor)
        {
            TextView tvWordItem = (TextView) view;
            tvWordItem.setText(cursor.getString(cursor.getColumnIndex("_id")));
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor)
        {
            setView(view, cursor);
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent)
        {
            //把布局檔案轉換為View對象
            View view = layoutInflater.inflate(R.layout.word_list_item, null);
            setView(view, cursor);
            return view;
        }

        public DictionaryAdapter(Context context, Cursor c, boolean autoRequery)
        {
            super(context, c, autoRequery);
            //通過系統服務獲得該內容相關的LayoutInflater對象
            layoutInflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
    }

    public void afterTextChanged(Editable s)
    {
        
        //  必須將english欄位的別名設為_id 
        Cursor cursor = database.rawQuery(
                "select english as _id from t_words where english like ?",
                new String[]
                { s.toString() + "%" });
        DictionaryAdapter dictionaryAdapter = new DictionaryAdapter(this,
                cursor, true);
        actvWord.setAdapter(dictionaryAdapter);

    }

    public void beforeTextChanged(CharSequence s, int start, int count,
            int after)
    {
        // TODO Auto-generated method stub

    }

    public void onTextChanged(CharSequence s, int start, int before, int count)
    {
        // TODO Auto-generated method stub

    }

    public void onClick(View view)
    {
        //從t_words的表中搜尋english為輸入框中的中文
        String sql = "select chinese from t_words where english=?";        
        Cursor cursor = database.rawQuery(sql, new String[]
        { actvWord.getText().toString() });
        String result = "未找到該單詞.";
        //  如果尋找單詞,顯示其中文的意思
        if (cursor.getCount() > 0)
        {
            //  必須使用moveToFirst方法將記錄指標移動到第1條記錄的位置
            cursor.moveToFirst();
            result = cursor.getString(cursor.getColumnIndex("chinese"));
        }
        //  顯示查詢結果對話方塊
        new AlertDialog.Builder(this).setTitle("查詢結果").setMessage(result)
                .setPositiveButton("關閉", null).show();

    }

    private SQLiteDatabase openDatabase()
    {
        try
        {
            // 獲得dictionary.db檔案的絕對路徑
            String databaseFilename = DATABASE_PATH + "/" + DATABASE_FILENAME;
            File dir = new File(DATABASE_PATH);
            // 如果/sdcard/dictionary目錄中存在,建立這個目錄
            if (!dir.exists())
                dir.mkdir();
            // 如果在/sdcard/dictionary目錄中不存在
            // dictionary.db檔案,則從res\raw目錄中複製這個檔案到
            // SD卡的目錄(/sdcard/dictionary)
            if (!(new File(databaseFilename)).exists())
            {
                // 獲得封裝dictionary.db檔案的InputStream對象
                InputStream is = getResources().openRawResource(
                        R.raw.dictionary);
                FileOutputStream fos = new FileOutputStream(databaseFilename);
                byte[] buffer = new byte[8192];
                int count = 0;
                // 開始複製dictionary.db檔案
                while ((count = is.read(buffer)) > 0)
                {
                    fos.write(buffer, 0, count);
                }

                fos.close();
                is.close();
            }
            // 開啟/sdcard/dictionary目錄中的dictionary.db檔案
            SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(
                    databaseFilename, null);
            return database;
        }
        catch (Exception e)
        {
        }
        return null;
    }

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.