文档章节

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

N3verL4nd
 N3verL4nd
发布于 2017/03/25 10:20
字数 1626
阅读 22
收藏 0

前言:

毕业设计的内容,只有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";
	
	@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;
			}
		});

		// 搜索按钮监听
		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();
				}

			}
		});
		// 清除按钮监听
		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();
			}
		}
	}

}


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;

	@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();
		}
	}
}


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


© 著作权归作者所有

N3verL4nd
粉丝 1
博文 379
码字总数 481243
作品 0
朝阳
私信 提问
北京GDG 7月 两场 Android 技术主题分享,金山、有道、知乎讲师…

7月21号和7月28号的下午将分别在京仪大酒店和车库咖啡举行两场 Android 技术分享,欢迎大家参加!有包括来自金山、有道、知乎等 Android 开发带来的技术分享。 1. 北京 GDG Android 技术分享...

韩国恺
2013/07/13
296
0
【android基础学习之二】——基础控件ListView

声明:学习的书籍《Android应用开发揭秘》,这里记录学习该书籍的日志,引用的相关代码与总结描述,没有商业的用途,完全是自我学习的一个记录,刚刚学习不可避免会出现很多问题,若是有错误...

晨曦之光
2012/03/08
666
0
BroadcastReceiver—学习

android broadcastReceiver学习 在实际应用中,我们常需要等,等待系统抑或其他应用发出一道指令,为自己的应用擦亮明灯指明方向。在Android中,充分考虑了广泛的这类需求,于是就有了Broad...

zt1212
2012/10/12
254
0
Python控制台英汉-汉英电子词典

Python控制台英汉-汉英电子词典 By qianghaohao(CodeNutter) 用python实现了下控制台电子词典,数据来自有道,通过向有道发送http表单数据,然后将服务器返回的json数据解析得到翻译结果,代...

CodeNutter
2016/08/08
43
0
把词典功能做到极致——欧路词典

tou 电子词典除了先天的搜索优势,总是被人诟病:词义不够详细、内容排版不像纸质词典那么美观。 「有道词典」、「金山词霸」都在有意弥补这些缺陷。但做到极致的还是「欧路词典」。 本篇文章...

沉思CONTEMPLATE
2017/11/12
0
0

没有更多内容

加载失败,请刷新页面

加载更多

OpenStack 简介和几种安装方式总结

OpenStack :是一个由NASA和Rackspace合作研发并发起的,以Apache许可证授权的自由软件和开放源代码项目。项目目标是提供实施简单、可大规模扩展、丰富、标准统一的云计算管理平台。OpenSta...

小海bug
昨天
5
0
DDD(五)

1、引言 之前学习了解了DDD中实体这一概念,那么接下来需要了解的就是值对象、唯一标识。值对象,值就是数字1、2、3,字符串“1”,“2”,“3”,值时对象的特征,对象是一个事物的具体描述...

MrYuZixian
昨天
6
0
数据库中间件MyCat

什么是MyCat? 查看官网的介绍是这样说的 一个彻底开源的,面向企业应用开发的大数据库集群 支持事务、ACID、可以替代MySQL的加强版数据库 一个可以视为MySQL集群的企业级数据库,用来替代昂贵...

沉浮_
昨天
6
0
解决Mac下VSCode打开zsh乱码

1.乱码问题 iTerm2终端使用Zsh,并且配置Zsh主题,该主题主题需要安装字体来支持箭头效果,在iTerm2中设置这个字体,但是VSCode里这个箭头还是显示乱码。 iTerm2展示如下: VSCode展示如下: 2...

HelloDeveloper
昨天
7
0
常用物流快递单号查询接口种类及对接方法

目前快递查询接口有两种方式可以对接,一是和顺丰、圆通、中通、天天、韵达、德邦这些快递公司一一对接接口,二是和快递鸟这样第三方集成接口一次性对接多家常用快递。第一种耗费时间长,但是...

程序的小猿
昨天
10
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部