使用Android简单实现有道电子词典
前言:
毕业设计的内容,仅仅有Java基础。没学过Android。
本着用到什么学什么。花费了10多个晚上完毕毕业设计。
当然,仅仅是简单的实线了电子词典功能,自始至终没有考虑过性能等问题。
本电子词典的数据文件是不错的,有道的API是分析有道电子词典的日志文件得到的,离线的柯林斯词典是Mdict词典的MDX文件转换(https://bitbucket.org/xwang/mdict-analysis)来的。这个是本电子词典的唯一亮点吧。由于我一直认为数据比界面更重要。
文件布局:
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveF9peWE=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">
核心文件介绍例如以下:
布局界面:
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"; @Override
protected 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();
// }
} @Override
protected 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);
} @Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (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.jpg
private 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;
}
};
};
@Override
protected 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;\">"; @Override
public 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() { @Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) { dictName = adapter.getItem(position);
} @Override
public void onNothingSelected(AdapterView<? > parent) { dictName = dict[0];
}
});
} public void setListener() // 设置监听器
{
Ibtnbook.setOnClickListener(new OnClickListener() {
@Override
public 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() { @Override
public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER) {
new Thread(new Runnable() { @Override
public void run() {
Search(); }
}).start();
wvShow.setFocusable(true);
wvShow.setFocusableInTouchMode(true);
wvShow.requestFocus();
}
return false;
}
}); // 搜索button监听
btnSrarch.setOnClickListener(new OnClickListener() { @Override
public 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() { @Override
public void run() {
Search(); }
}).start(); wvShow.setFocusable(true);
wvShow.setFocusableInTouchMode(true);
wvShow.requestFocus();
} }
});
// 清除button监听
btnClear.setOnClickListener(new OnClickListener() { @Override
public 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();
}
}
} }
翻译界面:
public class TransFragment extends Fragment { private InputMethodManager imm;
private EditText etSentence;
private TextView tvSentence;
private Button btnDel;
private Button btnTrans;
private View view; @Override
public 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() { @Override
public void onClick(View v) {
// TODO Auto-generated method stub
new Thread(new Runnable() { @Override
public void run() {
Research(); }
}).start();
etSentence.setFocusable(true);
etSentence.setFocusableInTouchMode(true);
etSentence.requestFocus();
}
}); btnDel.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
// TODO Auto-generated method stub
etSentence.setText("");
etSentence.setFocusable(true);
etSentence.setFocusableInTouchMode(true);
etSentence.requestFocus();
}
}); etSentence.setOnKeyListener(new OnKeyListener() { @Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER) {
new Thread(new Runnable() { @Override
public 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 block
e.printStackTrace();
}
}
}
使用Android简单实现有道电子词典的更多相关文章
- Android Webview实现有道电子词典
毕业设计android电子词典,先实现的一个小小的demo. 所谓的毕业设计就是用最短的时间学习一门语言,做出一个小的project. activity_main.xml <LinearLayo ...
- C++第15周(春)项目3 - OOP版电子词典(一)
课程首页在:http://blog.csdn.net/sxhelijian/article/details/11890759.内有完整教学方案及资源链接 [项目3-OOP版电子词典](本程序中须要的相 ...
- 第14周 项目三-OOP版电子词典
做一个简单的电子词典.在文件dictionary.txt中,保存的是英汉对比的一个词典,词汇量近8000个,英文.中文释义与词性间用'\t'隔开. (1)编程序,由用户输入英文词.显示词性和中文释义. ...
- wxWidgets+wxSmith版电子词典
课程首页在:http://blog.csdn.net/sxhelijian/article/details/11890759,内有完整教学方案及资源链接 [项目3-OOP版电子词典](本程序须要的相关 ...
- Android 瘦身之道 ---- so文件
Android 瘦身之道 ---- so文件 [TOC] 1. 前言 目前Android 瘦身只有几个方面可以入手,因为apk的结构就已经固定了. res 目录下的资源文件.(通常是压缩图片,比如 矢 ...
- C++第15周(春)项目3 - OOP版电子词典(二)
课程首页在:http://blog.csdn.net/sxhelijian/article/details/11890759,内有完整教学方案及资源链接 [项目3-OOP版电子词典](本程序须要的相关 ...
- OOP版电子词典
输入代码: /* * Copyright (c) 2014, 烟台大学计算机学院 * All rights reserved. * 文件名:sum123.cpp * 作 者:林海云 * 完毕日期:20 ...
- Android 瘦身之道
Android 瘦身之道 ---- so文件 [TOC] 1. 前言 目前Android 瘦身只有几个方面可以入手,因为apk的结构就已经固定了. res 目录下的资源文件.(通常是压缩图片,比如 矢 ...
- 第十四周(OOP版电子词典)
/* *copyright(c) 2015,烟台大学计算机学院 *All rights reserved. *文件名:第十四周(OOP版电子词典) *作者:王忠 *完毕日期:2015.6.10 *版本 ...
随机推荐
- 基于visual Studio2013解决C语言竞赛题之0806平均分
题目
- MySQL主键添加/删除
2改动数据库和表的字符集alter database maildb default character set utf8;//改动数据库的字符集alter table mailtable defaul ...
- windows api 梳理
PathMatchSpec Function Searches a string using a Microsoft MS-DOS wild card match type. Syntax BOOL ...
- jquery 如何动态添加、删除class样式方法介绍
获取与设置样式 获取class和设置class都可以使用attr()方法来完成.例如使用attr()方法来获取p元素的class 取与设置样式 获取class和设置class都可以使用attr()方法 ...
- 怎样在Ubuntu中使用条件布局
我们知道现代手机能够随着手持的方位发生改变而使得手机的方位也随着发生改变.对有些应用来说,我们也希望手机的布局也能尾随发生变化.第二种情况是当我们的应用安装到不同屏幕尺寸的平台上,我们希望我们的布局会 ...
- iOS依据字符串计算UITextView高度
iOS计算字符串高度,有须要的朋友能够參考下. 方法一:ios7.0之前适用 /** @method 获取指定宽度width,字体大小fontSize,字符串value的高度 @param value ...
- BLE简介和Android BLE编程
一.BLE和BT区别 其实我知道许多程序员不太喜欢阅读除了代码以外的文档,因为有时这些过于冗长的文档对编程并没有更多的好处,有了协议,接口,demo差不多很多人就能写出很好质量的代码了.但其实更深入的 ...
- 《Java虚拟机原理图解》1.3、class文件里的訪问标志、类索引、父类索引、接口索引集合
讲完了class文件里的常量池,我们就相当于克服了class文件里最麻烦的模块了.如今,我们来看一下class文件里紧接着常量池后面的几个东西:訪问标志.类索引.父类索引.接口索引集合. 1. 訪问标 ...
- QDockWidget嵌套布局详解-实现Visual Studio布局
概述 许多工程软件,如Qt Creator,VS,matlab等,都是使用dock布局窗口,这样用户可以自定义界面,自由组合窗口. Qt的嵌套布局由QDockWidget完成,用Qt Creator拖 ...
- java 变长參数使用原则
1.java变长參数用...表示,如Print(String... args){ ... }; 2.假设一个调用既匹配一个固定參数方法.又匹配一个变长參数方法,则优先匹配固定參数的方法 3.假设一个 ...