Easy to implement Youdao electronic dictionary using Android

Source: Internet
Author: User

Preface:

The content of graduation design, only has the Java Foundation. Never learned Android.

In the spirit of what to learn. It took more than 10 evenings to finish the graduation project.

Of course, the simple solid line of the electronic dictionary function, from beginning to finish did not consider the performance and other issues.

This electronic dictionary data file is good, Youdao API is to analyze Youdao electronic dictionary log file obtained, Offline Collins dictionary is mdict dictionary MDX file conversion (https://bitbucket.org/xwang/mdict-analysis). This is the only highlight of this e-dictionary. Because I always thought the data was more important than the interface.

File layout:

Watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvef9pewe=/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/dissolve/70 /gravity/center ">

The following are examples of core files:

Layout Interface:


public class Mainactivity extends Fragmentactivity implements Onclicklistener {private ImageView dict_image;private ImageView translate_image;private ImageView account_image;private relativelayout dict_layout;private RelativeLayout Translate_layout;private relativelayout account_layout;private dictfragment dictfragment;private TransFragment Transfragment;private myfragment myfragment;private Fragmentmanager Fmanager; Sqlitedatabase db;private final String database_path = Android.os.Environment.getExternalStorageDirectory (). GetAbsolutePath () + "/mdict";p rivate final String database_filename = "dict.db"; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); FManager = Getsupportfragmentmanager (); Initviews ();d B = OpenDatabase ()//cursor cs = db.rawquery ("select * from Wordbook where WORD = ' reservation ', null);//while (Cs.movetonext ()) {//toast.maketext (Mainactivity.this, cs.getstring (3), 0). Show ();/ }} @Overrideprotected void OnDestroy () {db.close (); Super.ondestroy ();} public void Initviews () {dict_image = (ImageView) Findviewbyid (r.id.dict_image); translate_image = (ImageView) Findviewbyid (r.id.translate_image); account_image = (ImageView) Findviewbyid (r.id.account_image);d ict_layout = ( Relativelayout) Findviewbyid (r.id.dict_layout); translate_layout = (relativelayout) Findviewbyid (R.id.translate_ Layout), Account_layout = (relativelayout) Findviewbyid (r.id.account_layout);d Ict_layout.setbackgroundcolor ( Color.parsecolor ("#FDF5E6")); Translate_layout.setbackgroundcolor (Color.parsecolor ("#FDF5E6")); Account_ Layout.setbackgroundcolor (Color.parsecolor ("#FDF5E6"));d Ict_layout.setonclicklistener (this); Translate_ Layout.setonclicklistener (this); Account_layout.setonclicklistener (this);} @Overridepublic void OnClick (View v) {//TODO auto-generated method Stubswitch (V.getid ()) {case R.id.dict_layout:setchio Ceitem (0); break;case r.id.translate_layout:setchioceitem (1); Break;case R.id.account_layout:setchioceitem (2); break;default:break;}} public void Setchioceitem (int index) {fragmenttransaction transaction = Fmanager.begintransaction (); Clearchioce (); Hidefragments (transaction); switch (index) {case 0:dict_image.setimageresource (r.drawable.tab_dict_pressed);d ict_ Layout.setbackgroundcolor (Color.parsecolor ("#FDF5E6")), if (dictfragment = = null) {dictfragment = new dictfragment (); Transaction.add (R.id.content, dictfragment);} else {transaction.show (dictfragment);} Break;case 1:translate_image.setimageresource (r.drawable.tab_translate_pressed); Translate_ Layout.setbackgroundcolor (Color.parsecolor ("#FDF5E6")), if (transfragment = = null) {transfragment = new transfragment ( ); Transaction.add (R.id.content, transfragment);} else {transaction.show (transfragment);} Break;case 2:account_image.setimageresource (r.drawable.tab_account_pressed); Account_layout.setbackgroundcolor ( Color.parsecolor ("#FDF5E6")), if (myfragment = = null) {myfragment = new myfragment (); Transaction.add (R.id.content, myfragment);} else {transaction.show (myfragment);} Break;default:break;} Transaction.commit ();} public void Clearchioce () {Dict_image.setimageresource (r.drawable.tab_dict_normal);d Ict_layout.setbackgroundcolor (Color.parsecolor ("#FDF5E6")); Translate_image.setimageresource (r.drawable.tab_translate_normal); Translate_ Layout.setbackgroundcolor (Color.parsecolor ("#FDF5E6")); Account_image.setimageresource (R.drawable.tab_account_ normal); Account_layout.setbackgroundcolor (Color.parsecolor ("#FDF5E6"));} public void Hidefragments (Fragmenttransaction transaction) {if (dictfragment! = null) {transaction.hide (dictfragment);} if (transfragment! = null) {transaction.hide (transfragment);} if (myfragment! = null) {transaction.hide (myfragment);}} Public Sqlitedatabase OpenDatabase () {try {String databasefilename = Database_path + "/" + D            Atabase_filename;            File dir = new file (Database_path);            if (!dir.exists ()) Dir.mkdir (); if (! (       New File (DatabaseFileName)). Exists ())     {InputStream is = Getresources (). Openrawresource (r.raw.dict);                FileOutputStream fos = new FileOutputStream (databasefilename);                byte[] buffer = new byte[8192];                                int count = 0;                while ((count = is.read (buffer)) > 0) {fos.write (buffer, 0, count);                } fos.close ();            Is.close ();            } sqlitedatabase Database = Sqlitedatabase.openorcreatedatabase (databasefilename, NULL);        return database;    } catch (Exception e) {} return null; }}

a daily interface:


public class Start extends Activity {private ImageView ivstart;private simpledateformat sdf;private String date;//http:// Cdn.iciba.com/web/news/longweibo/imag/2015-05-03.jpgprivate static final String url = "Http://cdn.iciba.com/web/news              /longweibo/imag/";p rivate Handler handle = new Handler () {public void Handlemessage (Message msg) {                  Switch (msg.what) {case 0:bitmap bmp= (Bitmap) msg.obj;                  Ivstart.setimagebitmap (BMP);              Break      }          };  }; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.start_layout); Ivstart = (ImageView) Findviewbyid (r.id.ivstart); SDF = new SimpleDateFormat ("Yyyy-mm-dd");              Date = Sdf.format (new Java.util.Date ()),//system.out.println (date), New Thread (new Runnable () {@Override           public void Run () {Bitmap bmp = Geturlimage (url + date + ". jpg");       Message msg = new Message ();                  Msg.what = 0;                  Msg.obj = BMP;              Handle.sendmessage (msg);  }}). Start (); Handler Handler = new Handler () handler.postdelayed (New Splashhandler (), 10000);} Class Splashhandler implements runnable{public void run () {startactivity (new Intent (Getapplicati              On (), Mainactivity.class));          Start.this.finish ();          }//Download Network picture public Bitmap geturlimage (String URL) {Bitmap bmp = null;              try {URL myurl = new URL (URL);              Get connected HttpURLConnection conn = (httpurlconnection) myurl.openconnection ();              Conn.setconnecttimeout (6000);//Set timeout Conn.setdoinput (true);              Conn.setusecaches (false);//Do not cache conn.connect ();              InputStream is = Conn.getinputstream ();//data stream for picture bmp = Bitmapfactory.decodestream (IS);          Is.close (); } CATCH (Exception e) {e.printstacktrace ();      } return BMP; }  }


Word query interface:


public class Dictfragment extends Fragment {MediaPlayer mediaplayer;private View view;//private TextView tvus;//Private TextView tvuk;private ImageButton ibtnbook;private button btnsrarch;private button btnclear;private EditText etinput; Private WebView wvshow;private inputmethodmanager imm;private Spinner spinner;private string Dictname;private string Basicmeaning;private arrayadapter<string> adapter;private final String Database_path = Android.os.Environment.getExternalStorageDirectory (). GetAbsolutePath () + "/mdict";p rivate final String database_ FILENAME = "Dict.db";p rivate static final string[] Dict = {"Basic interpretation", "Collins Dictionary of English and Chinese", "21st century English-Chinese Dictionary", "English-English Interpretation", "professional Interpretation", "Network Interpretation", "the same word  "," with synonyms "," bilingual Example "," original Example "," authoritative example "," encyclopedia "};p rivate static final string[] Dicts = {" EC "," Collins "," Ec21 "," ee "," special ", "Web_trans", "Rel_word", "Syno", "Blng_sents_part", "Media_sents_part", "Auth_sents_part", "Baike"};p rivate static Final String linkcss = "<link rel=\" stylesheet\ "href=\" File:///android_asseT/css/style.css\ "type=\" text/css\ ">";p rivate static final String BODY = "

> Parent) {dictname = dict[0];}});} public void Setlistener ()//Set Listener {Ibtnbook.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick ( View v) {String databasefilename = Database_path + "/" + database_filename; Sqlitedatabase db = Getactivity (). Openorcreatedatabase (DatabaseFileName, context.mode_private, NULL); Cursor cs = db.rawquery ("select * from Wordbook where word=?")

", new string[] {etinput.gettext (). toString (). Trim ()}), if (Cs.movetofirst ()) {Toast.maketext (getactivity ()," already exists ", Toast.length_short). Show ();} else {db.execsql ("INSERT into Wordbook (word,meaning) VALUES (?

,?) ", new object[] {etinput.gettext (). toString (). Trim (), basicmeaning}); Toast.maketext (Getactivity (), "already joined", Toast.length_short). Show (); Db.close ();}}); /Keyboard Listener Etinput.setonkeylistener (new Onkeylistener () {@Overridepublic Boolean onKey (View v, int keycode, keyevent event) {i F (keycode = = keyevent.keycode_enter) {New Thread (new Runnable () {@Overridepublic void run () {Search ();}). Start (); Wvshow.setfocusable (true); Wvshow.setfocusableintouchmode (true); Wvshow.requestfocus ();} return false;}); /Search button Listener Btnsrarch.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) {String word = Etinput.gettext (). toString (); word = Word.trim (); if (word.length () = = 0) {Toast.maketext (getactivity (), "Query content is empty", Toast.length_long). Show ();} else {//String urlstring =//"Http://dict.youdao.com/m/search?

keyfrom=dict.mindex&vendor=&q= "+//word;//String urlstring =" Http://m.youdao.com/dict?

Le=eng&q= "//+ word;//Wvshow.loadurl (urlstring); new Thread (New Runnable () {@Overridepublic void run () {Search ()}). Start (); Wvshow.setfocusable (true); Wvshow.setfocusableintouchmode (true); Wvshow.requestfocus ();}}); /Clear button listener Btnclear.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) {Etinput.settext ( "");}});} public void Selectdict () {for (int i = 0; i < dict.length; i++) {if (Dictname = = Dict[i]) {dictname = Dicts[i];break;} }}public void Search () {selectdict ();//Soft keyboard turned off. Turn off the IMM = (Inputmethodmanager) getactivity (). Getsystemservice (Context.input_method_service); if (Imm.isactive ()) { Imm.togglesoftinput (inputmethodmanager.show_implicit,inputmethodmanager.hide_not_always);} if (Dictname = = "EC") {//Basic interpretation using an additional interface basicmeaning = ""; String Word = Etinput.gettext (). toString (). Trim (); StringBuffer buffer = new StringBuffer (); Buffer.append ("



DescriptioncodeTranslation Interface:



public class Transfragment extends Fragment {private Inputmethodmanager imm;private EditText etsentence;private TextView Tvsentence;private button Btndel;private button btntrans;private View view, @Overridepublic view Oncreateview ( Layoutinflater Inflater, ViewGroup container,bundle savedinstancestate) {view = Inflater.inflate (R.layout.trans_ Fragment, container, false); Initviews (); Setlistener (); return view;} public void Initviews () {etsentence = (EditText) View.findviewbyid (r.id.etsentence); tvsentence = (TextView) View.findviewbyid (r.id.tvsentence); Btntrans = (Button) View.findviewbyid (R.id.btntrans); Btndel = (Button) View.findviewbyid (R.id.btndel);} public void Setlistener () {Btntrans.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) {// TODO auto-generated Method Stubnew Thread (new Runnable () {@Overridepublic void Run () {()}). Start (); Etsentence.setfocusable (true); Etsentence.setfocusableintouchmode (true); Etsentence.requestfocus ();}}); Btndel.setonclicKlistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated method Stubetsentence.settext (""); Etsentence.setfocusable (true); Etsentence.setfocusableintouchmode (true); Etsentence.requestfocus ();}}); Etsentence.setonkeylistener (New Onkeylistener () {@Overridepublic Boolean onKey (View v, int keycode, keyevent event) {if ( KeyCode = = keyevent.keycode_enter) {New Thread (new Runnable () {@Overridepublic void Run () {()}). Start (); Etsentence.setfocusable (true); Etsentence.setfocusableintouchmode (true); Etsentence.requestfocus ();} return false;}}); public void Inputmethodmanager () {IMM = () getactivity (). Getsystemservice (Context.input_method_service); if ( Imm.isactive ()) {imm.togglesoftinput (inputmethodmanager.show_implicit,inputmethodmanager.hide_not_always);} Getstringfromweb json = new Getstringfromweb (); try {String word = Etsentence.gettext (). toString (). Trim (); Json.setjson ( Word, "", 1); Jsonobject jsonobject = new Jsonobject (Json.getjson ()); Jsonarray TRansresult = Jsonobject.getjsonarray ("Trans_result"); String DST = ""; for (int i = 0; I < transresult.length (); i++) {Jsonobject jsons = (jsonobject) transresult.get (i);d st + = jsons.getstring ("DST");} Tvsentence.settext (DST);} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}


Source File Download: http://pan.baidu.com/s/1m9P3w


Easy to implement Youdao electronic dictionary using Android

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.