词典

来源:互联网 发布:电脑日历备忘录软件 编辑:程序博客网 时间:2024/04/27 18:53

Dictionary.java

import java.io.File;import java.io.FileOutputStream;import java.io.InputStream;import com.bzu.gxs.dao.DictionaryAdapter;import com.bzu.gxs.db.DBHelper;import com.bzu.gxs.R;import android.app.Activity;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.util.Log;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 Dictionary extends Activity implements OnClickListener,TextWatcher {private DBHelper dbHelper; // 用户输入文本框private AutoCompleteTextView word; // 定义数据库的名字private SQLiteDatabase database;private Button searchWord; // 搜索按钮private TextView showResult; // 用户显示查询结果@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);dbHelper = new DBHelper(getBaseContext());// 打开数据库database = dbHelper.openDatabase();init();searchWord.setOnClickListener(this); // 绑定监听器word.addTextChangedListener(this); // 绑定文字改变监听器}public void init() {searchWord = (Button) findViewById(R.id.btnSearch);word = (AutoCompleteTextView) findViewById(R.id.etWord);showResult = (TextView) findViewById(R.id.tvSearchResult);}public void afterTextChanged(Editable s) {Cursor cursor = database.rawQuery("select english as _id from t_words where english like ?",new String[] { s.toString() + "%" });// 新建新的AdapterDictionaryAdapter dictionaryAdapter = new DictionaryAdapter(this,cursor, true);// 绑定适配器word.setAdapter(dictionaryAdapter);}public void beforeTextChanged(CharSequence s, int start, int count,int after) {}public void onTextChanged(CharSequence s, int start, int before, int count) {}public void onClick(View view) {// 查询指定的单词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) { cursor.moveToFirst(); // 须使用moveToFirst方法将记录指针移动到第1条记录的位置result = cursor.getString(cursor.getColumnIndex("chinese")).replace("&", "&");}showResult.setText(word.getText() + "\n" + result.toString());// 将结果显示到TextView中}}


DictionaryAdapter.java

import android.content.Context;import android.database.Cursor;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.CursorAdapter;import android.widget.TextView;import com.bzu.gxs.R;//自定义Adapter类public class DictionaryAdapter extends CursorAdapter {private LayoutInflater layoutInflater;@Overridepublic 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")));}// 绑定选项到列表中@Overridepublic void bindView(View view, Context context, Cursor cursor) {setView(view, cursor);}// 生成新的选项@Overridepublic View newView(Context context, Cursor cursor, ViewGroup parent) {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) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);}}


DBHelper.java

import java.io.File;import java.io.FileOutputStream;import java.io.InputStream;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import com.bzu.gxs.R;public class DBHelper {//定义数据库的存放路径private final String DATABASE_PATH = android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+ "/dictionary";private final String DATABASE_FILENAME = "dictionary.db";private Context context;public DBHelper(Context context) {this.context = context;}public 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 = context.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){}//如果打开出错,则返回nullreturn null;}}


UI设计

<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:background="@drawable/mainbg"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context=".MainActivity" >    <AutoCompleteTextView        android:id="@+id/etWord"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentLeft="true"        android:layout_alignParentTop="true"        android:layout_marginTop="31dp"        android:background="@android:drawable/edit_text"        android:ems="10"        android:hint="@string/searchHint"        android:singleLine="true"        android:textColor="#552006"        android:textColorHint="#782f10" >    </AutoCompleteTextView>    <Button        android:id="@+id/btnSearch"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignBaseline="@+id/etWord"        android:layout_alignBottom="@+id/etWord"        android:layout_marginLeft="16dp"        android:layout_toRightOf="@+id/etWord"        android:background="@drawable/ibsearchword"        android:onClick="searchWord"        android:text="@string/serachWord" />    <TextView        android:id="@+id/tvSearchResult"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:layout_alignLeft="@+id/etWord"        android:layout_below="@+id/etWord"        android:layout_marginTop="22dp"        android:textSize="25sp"        android:background="@drawable/bg_roundcorner"        android:textAppearance="?android:attr/textAppearanceMedium" /></RelativeLayout>


 

0 0