使用Android简单实现有道电子词典

news/2024/11/23 13:15:26/

前言:

毕业设计的内容,只有Java基础,没学过Android。

本着用到什么学什么,花费了10多个晚上完成毕业设计。

当然,只是简单的实线了电子词典功能,自始至终没有考虑过性能等问题。

本电子词典的数据文件是不错的,有道的API是分析有道电子词典的日志文件得到的,离线的柯林斯词典是Mdict词典的MDX文件转换(https://bitbucket.org/xwang/mdict-analysis)来的。这个是本电子词典的唯一亮点吧,因为我一直觉得数据比界面更重要。

文件布局:


核心文件介绍如下:

布局界面:


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";private final String DATABASE_FILENAME = "dict.db";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);fManager = getSupportFragmentManager();initViews();db = 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);dict_layout = (RelativeLayout) findViewById(R.id.dict_layout);translate_layout = (RelativeLayout) findViewById(R.id.translate_layout);account_layout = (RelativeLayout) findViewById(R.id.account_layout);dict_layout.setBackgroundColor(Color.parseColor("#FDF5E6"));translate_layout.setBackgroundColor(Color.parseColor("#FDF5E6"));account_layout.setBackgroundColor(Color.parseColor("#FDF5E6"));dict_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:setChioceItem(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);dict_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);dict_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 + "/" + DATABASE_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;}
}

每日一句界面:


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/";private 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(getApplication(),MainActivity.class));  Start.this.finish();  }  }//下载网络图片public Bitmap getURLimage(String url) {  Bitmap bmp = null;  try {  URL myurl = new URL(url);  // 获得连接  HttpURLConnection conn = (HttpURLConnection) myurl.openConnection();  conn.setConnectTimeout(6000);//设置超时  conn.setDoInput(true);  conn.setUseCaches(false);//不缓存  conn.connect();  InputStream is = conn.getInputStream();//获得图片的数据流  bmp = BitmapFactory.decodeStream(is);  is.close();  } catch (Exception e) {  e.printStackTrace();  }  return bmp;  }  
}


单词查询界面:


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";private final String DATABASE_FILENAME = "dict.db";private static final String[] dict = { "基本释义", "柯林斯英汉双解大辞典", "21世纪大英汉词典","英英释义", "专业释义", "网络释义", "同根词", "同近义词", "双语例句", "原声例句", "权威例句", "百科" };private static final String[] dicts = { "ec", "collins", "ec21", "ee","special", "web_trans", "rel_word", "syno", "blng_sents_part","media_sents_part", "auth_sents_part", "baike" };private static final String linkCss = "<link rel=\"stylesheet\" href=\"file:///android_asset/css/style.css\" type=\"text/css\">";private static final String body = "<html><head>" + linkCss+ "</head><body class=\"p-dict\" style=\"height: 591px;\">";@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {view = inflater.inflate(R.layout.dict_fragment, container, false);InitViews();setListener();// 内部打开连接wvShow.setWebViewClient(new WebViewClient() {public boolean shouldOverrideUrlLoading(WebView view, String url) {view.loadUrl(url);return true;}});// 滚动条wvShow.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);return view;}// 初始化public void InitViews() {btnSrarch = (Button) view.findViewById(R.id.btnSearch);btnClear = (Button) view.findViewById(R.id.btnClear);etInput = (EditText) view.findViewById(R.id.etInput);wvShow = (WebView) view.findViewById(R.id.wvShow);// tvUs = (TextView) view.findViewById(R.id.tvUs);// tvUk = (TextView) view.findViewById(R.id.tvUk);Ibtnbook = (ImageButton) view.findViewById(R.id.Ibtnbook);wvShow.getSettings().setDefaultTextEncodingName("UTF-8");spinner = (Spinner) view.findViewById(R.id.sp);adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_item, dict);adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);spinner.setAdapter(adapter);spinner.setOnItemSelectedListener(new OnItemSelectedListener() {@Overridepublic void onItemSelected(AdapterView<?> parent, View view,int position, long id) {dictName = adapter.getItem(position);}@Overridepublic void onNothingSelected(AdapterView<?> parent) {dictName = dict[0];}});}public void setListener() // 设置监听器{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(), "已经存在", Toast.LENGTH_SHORT).show();} else {db.execSQL("insert into wordbook(word,meaning) values(?,?)",new Object[] { etInput.getText().toString().trim(),basicMeaning });Toast.makeText(getActivity(), "已经添加", Toast.LENGTH_SHORT).show();}db.close();}});// 键盘监听etInput.setOnKeyListener(new OnKeyListener() {@Overridepublic boolean onKey(View v, int keyCode, KeyEvent event) {if (keyCode == KeyEvent.KEYCODE_ENTER) {new Thread(new Runnable() {@Overridepublic void run() {Search();}}).start();wvShow.setFocusable(true);wvShow.setFocusableInTouchMode(true);wvShow.requestFocus();}return false;}});// 搜索按钮监听btnSrarch.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {String word = etInput.getText().toString();word = word.trim();if (word.length() == 0) {Toast.makeText(getActivity(), "查询内容为空", 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();}}});// 清除按钮监听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();// 软键盘开启则关闭,关闭则开启imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);if (imm.isActive()) {imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,InputMethodManager.HIDE_NOT_ALWAYS);}if (dictName == "ec") { // 基本释义使用另外的接口basicMeaning = "";String word = etInput.getText().toString().trim();StringBuffer buffer = new StringBuffer();buffer.append("<html><head></head><body>");GetStringFromWeb json = new GetStringFromWeb();try {json.setJson(word, "", 3);JSONObject jsonObject = new JSONObject(json.getJson());JSONObject basic = jsonObject.getJSONObject("basic");// tvUs.setText("美:[" + basic.getString("us-phonetic") + "]");// tvUk.setText("英:[" + basic.getString("uk-phonetic") + "]");buffer.append("美:[" + basic.getString("us-phonetic") + "]");buffer.append("英:[" + basic.getString("uk-phonetic") + "]");JSONArray explains = basic.getJSONArray("explains");// System.out.println("here");for (int i = 0; i < explains.length(); i++) {buffer.append(explains.getString(i) + "<br>");basicMeaning += explains.getString(i);}buffer.append("</body></html>");wvShow.loadDataWithBaseURL("", buffer.toString(), "text/html","UTF-8", "");} catch (Exception e) {e.printStackTrace();}} else {GetStringFromWeb json = new GetStringFromWeb();String word = etInput.getText().toString().trim();try {json.setJson(word, dictName, 2);String html = body + "<div id=\"" + dictName + "\" "+ "class=\"trans-container " + dictName + "\">"+ json.getJson() + "</div></body></html>";// wvShow.getSettings().setDefaultTextEncodingName("UTF-8");wvShow.loadDataWithBaseURL("http://m.youdao.com/", html,"text/html", "UTF-8", null);// System.out.println(html);} catch (Exception e) {e.printStackTrace();}}}}


Description
Code

翻译界面:



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() {Research();}}).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() {Research();}}).start();etSentence.setFocusable(true);etSentence.setFocusableInTouchMode(true);etSentence.requestFocus();}return false;}});}public void Research() {imm = (InputMethodManager) 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);dst += jsons.getString("dst");}tvSentence.setText(dst);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}
}


源文件下载:http://pan.baidu.com/s/1m9P3w


转载于:https://www.cnblogs.com/lgh1992314/p/5834733.html


http://www.ppmy.cn/news/253932.html

相关文章

有道词典java下载电脑版下载手机版下载安装_有道词典下载安装_有道词典app下载「官方版」-太平洋下载中心...

有道词典app是网易有道出品的互联网时代词典软件&#xff0c;是最好用的免费全能翻译软件&#xff0c;也是最受欢迎的词典软件。有道词典手机版目前已经有超过5亿用户。有道词典下载本地增强版是可随身携带的多语种互译词典&#xff0c;离线时也可轻松查询&#xff0c;内置超过…

有道词典

很喜欢使用有道词典进行查阅&#xff0c;现在也想自己试着仿照它做一个有道词典 首先界面需要EditText,Button,WebView 和Toast 四个控件 主要布局文件&#xff1a; <RelativeLayout xmlns:android"http://schemas.android.com/apk/res/android"xmlns:tools…

放弃有道词典和有道云笔记

放弃有道词典&#xff08;移动版&#xff09;&#xff1a; 我在用有道词典之前是一直用欧路词典的&#xff0c;一次更换安卓手机后去下载欧路&#xff0c;偶然看到有道词典&#xff0c;发现它的下载量远远远远地超过了欧路&#xff0c;用户评价也都挺好&#xff0c;就临时决定…

Manjaro安装有道词典,启动报错解决

文章目录 问题解决过程总结 问题 最近鼓捣scrcpy投屏手机的时候&#xff0c;都是去官方仓库看readme&#xff0c;全英文文档&#xff0c;总有些不认识的单词&#xff0c;于是想着整个词典&#xff0c;就想到了有道词典。安装过程很顺利&#xff0c;结果安装完之后启动不了&…

欢Ubuntu 16.04有道词典安装

Ubuntu 16.04有道词典安装 1.下载.deb包 官方下载地址&#xff1a;http://cidian.youdao.com/index-linux.html 2.安装有道词典&#xff1a; 进入.deb包所在目录终端&#xff1a; sudo dpkg -i youdao-dict_1.1.0-0-deepin_amd64.deb 3.执行上面命令可能出现缺少依赖&#xff…

android简单的有道词典开发

简单的android有道词典开发 第一次写教程&#xff0c;不好勿怪哈&#xff01;其实想写这篇教程已经很久了&#xff0c;但却一直没有付诸行动&#xff0c;这个项目是偶然间在论坛里发现的&#xff0c;我算是弄出来整理了一下吧&#xff01;所以在此要感谢那些前辈们&#xff0c…

有道词典java下载电脑版下载手机版下载安装_网易有道词典下载-网易有道词典 安卓版v8.3.4-PC6安卓网...

有道词典手机版是网易出品的一款词典软件&#xff0c;即便你不学习英语&#xff0c;有道词典手机版也是你不愿错过的一款app&#xff0c;有道词典手机版在同类软件中可以算是非常不错的存在了&#xff0c;休闲的时候翻一翻&#xff0c;会找到一些有趣的内容。 功能介绍 - 支持中…

有道词典java下载电脑版下载手机版下载安装_【有道词典官方下载】有道词典PC版下载_多特软件站...

【有道词典概括介绍】 一款很小很强大的翻译软件。2345软件大全提供有道词典官方下载&#xff0c;有道词典PC版下载。 【有道词典基本介绍】 有道词典是网易有道出品的一款很小很强大的翻译软件&#xff0c;通过独创的网络释义功能&#xff0c;轻松囊括互联网上的流行词汇与海量…