使用Android簡單實現有道電子詞典

weixin_34377065發表於2016-01-10

前言:

畢業設計的內容,僅僅有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


相關文章