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

前言:

毕业设计的内容,仅仅有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; } }); // 搜索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(); } } } }



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


转载于:https://www.cnblogs.com/lcchuguo/p/5119650.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值