天天看点

Android实现简单的电子词典

使用AutoCompleteTextView,词典数据保存在小型数据库sqlite中,在res的raw文件夹下,运行改程序会自动复制到手机内置SD卡下。

本地电子词典保存在数据库中,源文件代码在http://download.csdn.net/detail/bq1073100909/8079045

添加对SD卡的读写权限:

<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
           

MainActivity.java

package org.dyb.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

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

public class MainActivity extends Activity implements OnClickListener,
		TextWatcher {
	// 定义数据库的存放路径
	 private final String DATABASE_PATH = android.os.Environment
			 .getExternalStorageDirectory().getAbsolutePath() + "/dictionary";
	// 用户输入文本框
	private AutoCompleteTextView word;
	// 定义数据库的名字
	private final String DATABASE_FILENAME = "dictionary.db";
	private SQLiteDatabase database;
	private Button searchWord;
	// 用户显示查询结果
	private TextView showResult;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		// 打开数据库
		database = openDatabase();
		searchWord = (Button) findViewById(R.id.searchWord);
		word = (AutoCompleteTextView) findViewById(R.id.word);
		// 绑定监听器
		searchWord.setOnClickListener(this);
		word.addTextChangedListener(this);
		showResult = (TextView) findViewById(R.id.result);
	}

	public class DictionaryAdapter extends CursorAdapter {
		private LayoutInflater layoutInflater;

		public DictionaryAdapter(Context context, Cursor c, boolean flags) {
			super(context, c, flags);
			layoutInflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		@Override
		public CharSequence convertToString(Cursor cursor) {
			return cursor == null ? "" : cursor.getString(cursor
					.getColumnIndex("_id"));
		}

		// 生成新的选项
		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			View view = layoutInflater.inflate(R.layout.word_list_item, null);
			setView(view, cursor);
			return view;
		}

		// 绑定选项到列表中
		@Override
		public void bindView(View view, Context context, Cursor cursor) {
			setView(view, cursor);
		}

		// 将单词信息显示到列表中
		private void setView(View view, Cursor cursor) {
			TextView tvWordItem = (TextView) view;
			tvWordItem.setText(cursor.getString(cursor.getColumnIndex("_id")));
		}

	}

	// 打开数据库
	private SQLiteDatabase openDatabase() {
		try {
			// 获得dictionary.db文件的绝对路径
			String databaseFilename = DATABASE_PATH + "/" + DATABASE_FILENAME;
			File dir = new File(DATABASE_PATH);
			// 如果目录不存在,则创建这个目录
			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) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public void onClick(View v) {
		// 查询指定的单词
		String sql = "select chinese from t_words where english=?";
		Cursor cursor = database.rawQuery(sql, new String[] { word.getText()
				.toString() });
		String result = "未找到该单词.";
		// 如果查找单词,显示其中文的意思
		if (cursor.getCount() > 0) {
			// 必须使用moveToFirst方法将记录指针移动到第1条记录的位置
			cursor.moveToFirst();
			result = cursor.getString(cursor.getColumnIndex("chinese"))
					.replace("&", "&");
		}
		// 将结果显示到TextView中
		showResult.setText(word.getText() + "\n" + result.toString());
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {

	}

	@Override
	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() + "%" });
		// 新建新的Adapter
		DictionaryAdapter dictionaryAdapter = new DictionaryAdapter(this,
				cursor, true);
		// 绑定适配器
		word.setAdapter(dictionaryAdapter);
	}

}
           

布局文件:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    >
    <!-- 使用RelativeLayout布局用于在一行中显示两个元素 -->
    <RelativeLayout 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/search"
        >
         <AutoCompleteTextView
            android:id="@+id/word"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_toLeftOf="@+id/searchWord"
            android:ems="20"
            android:singleLine="true" >
            <requestFocus />
        </AutoCompleteTextView>
		<!-- 搜索按钮,供用户点击查询单词 -->
        <Button
            android:id="@+id/searchWord"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:text="@string/searchWord" />
        
    </RelativeLayout>
    <TextView 
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="@string/searchLable"
        />
    <TextView 
        android:id="@+id/result"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.68"
        android:background="@color/white"
        android:textColor="@color/blue" />
        />
    
</LinearLayout>
           

word_list_item.xml

<?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:gravity="center_vertical"
    android:minHeight="?android:attr/listPreferredItemHeight"
    android:paddingLeft="6dip"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:textColor="@color/gray" />
           

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">字典</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
	<string name="searchWord">搜索</string>
	<string name="searchLable">查询结果</string>
</resources>