2015 Android Case tour case seven: electronic dictionary Knowledge Points:
1. Auto-complete text box (Autocompletetextview)
Autocompletetextview is derived from the EditText, when the user enters a certain character, Autocompletetextview will display a drop-down menu for the user to select, when the user selects a menu, The content is populated into the text.
Using Autocompletetextview, you need to set a adapter, which encapsulates the preset hint text adapter
2.SQLiteDataBase Database
3.Adapter Adapter
Documents involved:
Res->layout->activity_main.xml Layout file
Res->layout->word_list_item.xml Layout file
res->raw-> dictionary.db Dictionary Database
A string resource for the res->values->strings resource file
Res->values->color resource file Color resources
Res->androidmanifest.xml System manifest file main add SD card related permissions
Src->package->mainactivity.java java file
Activity_main.xml
<!--linear layout--><linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android" Android:layout_ Width= "Match_parent" android:layout_height= "match_parent" android:orientation= "vertical" android:background= "#ff8 08080 "> <!--relative layouts for setting the search box and search button-<relativelayout android:layout_width=" Match_parent "Android : layout_height= "Wrap_content" > <!--Define auto-complete text box for users to enter words--<autocompletetextview Android Oid:id= "@+id/word" android:layout_width= "match_parent" android:layout_height= "Wrap_content" Android:layout_alignparentleft= "true" android:ems= "android:layout_toleftof=" @+id/searchword "/ > <!--Search button for users to click on the word---<button android:id= "@+id/searchword" Android:la Yout_width= "Wrap_content" android:layout_height= "Wrap_content" android:layout_alignparenttop= "true" Android:layout_alignpaRentright= "true" android:text= "@string/search"/> </RelativeLayout> <!--query Result--<te Xtview android:layout_width= "match_parent" android:layout_height= "wrap_content" android:text= "@strin G/result "/> <!--users show results for queries-<textview android:id=" @+id/show "Android:layout_width=" Ma Tch_parent "android:layout_height=" match_parent "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 "/>
Mainactivity.java
Package Com.example.mydicitonary;import Java.io.file;import Java.io.fileoutputstream;import java.io.InputStream; Import Android.app.activity;import Android.content.context;import Android.database.cursor;import Android.database.sqlite.sqlitedatabase;import Android.os.bundle;import Android.support.v4.widget.CursorAdapter; Import Android.text.editable;import Android.text.textwatcher;import Android.util.log;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.textview;public class Mainactivity extends Activity {//define log label private static final String tag = "Dicitonar Y ";//Declaration Control Object Private Button search;private TextView show;private autocompletetextview actv;//used to sqlitedatebase// Defines the storage path for the database private static final String Datebase_path = Android.os.Environment.getExternalStorageDirectory (). GetAbsolutePath () + "/dictionary";//define the name of the database PrivaTe static final String datebase_name = "dictionary.db";p rivate sqlitedatabase database; @Overrideprotected void OnCreate ( Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); LOG.I (TAG, "Dicitonary is OnCreate");//Gets the control in the Layout init ();//Open Database = Opendatebase ();//listener Event handling Listener ();} /** * @oaram initialization control */private void init () {search = (Button) This.findviewbyid (R.id.searchword); show = (TextView) This.findviewbyid (r.id.show); ACTV = (Autocompletetextview) This.findviewbyid (R.id.word);} /** * @param handling listener event */private void Listener () {//button click event Search.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View arg0) {string result = "The word information not found";//Query the specified word String sql = "Select Chinese from t_words where english=?"; cursor cursor = database.rawquery (sql, New String[]{actv.gettext (). toString ()}); if (Cursor.getcount () >0) {// You must use the Movetofirst method to move the record pointer to the position of the 1th record Cursor.movetofirst (); result = Cursor.getstring (Cursor.getcolumnindex ("Chinese") ). Replace ("& "," & ");} Display the results in TextView Show.settext (Actv.gettext (). toString () + "\ n" +result);}); /text Change event Actv.addtextchangedlistener (new Textwatcher () {@Overridepublic void ontextchanged (charsequence arg0, int arg1, int arg2, int arg3) {//TODO auto-generated method stub} @Overridepublic void Beforetextchanged (charsequence arg0, int arg1 , int arg2,int arg3) {//TODO auto-generated method stub} @Overridepublic void Aftertextchanged (Editable s) {cursor cursor = Database.rawquery ("Select Chinese as _id from T_words where 中文版 like?", New string[]{s.tostring () + "%"});//New ad Apterdictionaryadapter dictionaryadapter = new Dictionaryadapter (Mainactivity.this,cursor, true);// Bind adapter Actv.setadapter (Dictionaryadapter);}});} Custom adapter class public class Dictionaryadapter extends cursoradapter{//for an interface that is not loaded or wants to be loaded dynamically, Need to be loaded using layoutinflater.inflate (), or//for an already loaded interface, you can use the Activiyt.findviewbyid () method to get the interface elements. Private Layoutinflater Layoutinflater;public Dictionaryadapter (context context, Cursor C, Boolean AutoREquery) {Super (context, C, autorequery); layoutinflater = (Layoutinflater) context.getsystemservice (context.layout_ Inflater_service);} @Overridepublic charsequence converttostring (cursor cursor) {return cursor = = null? "": Cursor.getstring (Cursor.getcolumnindex ("_id"));} Displays the word information to the list private void Setview (view view, cursor cursor) {TextView Tvworditem = (TextView) view;tvworditem.settext ( Cursor.getstring (Cursor.getcolumnindex ("_id"));} Bind options to the list @overridepublic void BindView (view view, context context, cursor cursor) {Setview (view, cursor);} @Overridepublic View Newview (context context, cursor cursor, viewgroup arg2) {View view = Layoutinflater.inflate (r.layout . Word_list_item, null); Setview (view, cursor); return view;}} /** * @param returns an Sqlitedatabase object * @return */private sqlitedatabase opendatebase () {try {//Get the absolute path of the Dictionary.db file string DatabaseFileName = Datebase_path + "/" + datebase_name; File dir = new file (datebase_path);//If/sdcard/dictionary directory exists, create this directory if (!dir.exists ()) dir.mkdir ();//ASIf the//dictionary.db file does not exist in the/sdcard/dictionary directory, copy this file from the Res\raw directory to//SD card directory (/sdcard/dictionary) if ( New file (DatabaseFileName)). Exists ()) {//Get the InputStream object that encapsulates the Dictionary.db file InputStream is = Getresources (). Openrawresource (r.raw.dictionary); FileOutputStream fos = new FileOutputStream (databasefilename); byte[] buffer = new Byte[9128];int count = 0;//start copying Dictiona Ry.db file while ((count = is.read (buffer))!=-1) {fos.write (buffer, 0, count);} Close file stream is.close (); Fos.close ();} Open the Dictionary.db file in the/sdcard/dictionary directory sqlitedatabase database = Sqlitedatabase.openorcreatedatabase ( DatabaseFileName, NULL); return database;} catch (Exception e) {//Todo:handle Exception}return null;}}
My Android Case-e-Dictionary