• Android Webview实现有道电子词典


    毕业设计android电子词典,先实现的一个小小的demo。

    所谓的毕业设计就是用最短的时间学习一门语言,做出一个小的project。

    activity_main.xml

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent" 
        android:orientation="vertical">
    
        <LinearLayout 
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:orientation="horizontal" >
            
            <TextView 
                android:id="@+id/tvDict"
                android:layout_width="0dp"
                android:layout_height="40dp"
                android:layout_weight="1"
                android:text="@string/tv_dict"
                />
            <Spinner 
                android:id="@+id/sp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="2"
                />
        </LinearLayout>
        
        
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="60dp"
            android:orientation="horizontal" >
            
            <EditText
                android:id="@+id/etInput"
            	android:layout_width="0dp"
            	android:layout_height="60dp"
            	android:layout_weight="3" 
            	android:text=""
            	android:hint=""/>
                
            <Button 
                android:id="@+id/btnSearch"
                android:layout_width="0dp"
            	android:layout_height="60dp"
            	android:layout_weight="1" 
            	android:text="@string/btn_search"
                />
            
            <Button 
                android:id="@+id/btnClear"
                android:layout_width="0dp"
            	android:layout_height="60dp"
            	android:layout_weight="1" 
            	android:text="@string/btn_clear"
                />
           
         </LinearLayout>
         
         <WebView 
             android:id="@+id/wvShow"
             android:layout_height="0dp"
             android:layout_width="fill_parent"
             android:layout_weight="4"
             android:focusable="false"
             />
    
    </LinearLayout>
    

    JsonString.java

    package com.example.webviewtest;
    
    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.Reader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    public class JsonString {
    	
    	private String json;
    	
    	JsonString(){
    		
    	}
    	
    	public void setStrJson(String json) {
    		this.json = json;
    	}
    	
    	public String getStrJson() {
    		return json;
    	}
    	
    public void setJsonString(String word)throws Exception{
    		
    		String urlPath = "http://fanyi.youdao.com/openapi.do?keyfrom=neverland&key=969918857&type=data&doctype=json&version=1.1&q=";
    		urlPath += word;
    		System.out.println(urlPath);
    		URL url = new URL(urlPath);
    		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    		connection.connect();
    		InputStream inputStream = connection.getInputStream();
    		Reader reader = new InputStreamReader(inputStream, "UTF-8");
    		BufferedReader bufferedReader = new BufferedReader(reader);
    		String str = null;
    		StringBuffer stringBuffer = new StringBuffer();
    		while((str = bufferedReader.readLine())!= null){
    			stringBuffer.append(str);
    		}
    		reader.close();
    		connection.disconnect();
    		json = stringBuffer.toString();
    	}
    	
    }
    

    HtmlString.java

    package com.example.webviewtest;
    
    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.Reader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    public class HtmlString {
    	
    	private String webString;
    	
    	HtmlString(){
    		
    	}
    	
    	public void setwebString(String webString) {
    		this.webString = webString;
    	}
    	
    	public String getwebString() {
    		return webString;
    	}
    	
    public void setwebString(String word, String dict)throws Exception{
    		
    		String urlPath = "http://m.youdao.com/singledict?le=eng&dict=";
    		urlPath = urlPath + dict + "&q=" + word;
    		//System.out.println(urlPath);
    		URL url = new URL(urlPath);
    		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    		connection.connect();
    		InputStream inputStream = connection.getInputStream();
    		Reader reader = new InputStreamReader(inputStream, "UTF-8");
    		BufferedReader bufferedReader = new BufferedReader(reader);
    		String str = null;
    		StringBuffer stringBuffer = new StringBuffer();
    		while((str = bufferedReader.readLine())!= null){
    			stringBuffer.append(str);
    		}
    		reader.close();
    		connection.disconnect();
    		webString = stringBuffer.toString();
    	}
    	
    }
    

    MainActivity.java

    package com.example.webviewtest;
    
    import android.support.v4.app.FragmentActivity;
    import android.os.Bundle;
    import android.view.KeyEvent;
    import android.view.View;
    import android.view.View.OnKeyListener;
    import android.webkit.WebView;
    import android.webkit.WebViewClient;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemSelectedListener;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Spinner;
    import android.widget.Toast;
    import android.view.View.OnClickListener;
    import android.view.inputmethod.InputMethodManager;
    import org.json.JSONObject;
    import org.json.JSONArray;
    
    public class MainActivity extends FragmentActivity {
    
    	private Button btnSrarch;
    	private Button btnClear;
    	private EditText etInput;
    	private WebView wvShow;
    	InputMethodManager imm;
    	private Spinner spinner;
    	private String dictName;
    	private ArrayAdapter<String> adapter;
    	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/style.css" type="text/css">";
    	
    	private static final String body = "<html><head>" + linkCss + "</head><body class="p-dict" style="height: 591px;">";
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);
    
    		InitViews();
    		setListener();
    
    		// 内部打开连接
    		wvShow.setWebViewClient(new WebViewClient() {
    			public boolean shouldOverrideUrlLoading(WebView view, String url) {
    				view.loadUrl(url);
    				return true;
    			}
    		});
    
    		// 滚动条
    		wvShow.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
    
    	}
    
    	public void Search() {
    		selectDict();
    		if (dictName == "ec") {         //基本释义使用另外的接口
    			String word = etInput.getText().toString().trim();
    			StringBuffer buffer = new StringBuffer();
    			buffer.append("<html><head><link rel="stylesheet" href="file:///android_asset/font.css" type="text/css"></head><body>");
    			JsonString json = new JsonString();
    			try {
    				json.setJsonString(word);
    				JSONObject jsonObject = new JSONObject(json.getStrJson());
    				JSONObject basic = jsonObject.getJSONObject("basic");
    				buffer.append("<p class="us-phonetic">us-phonetic:" + basic.getString("us-phonetic") + "</p><br>");
    				buffer.append("<p class="uk-phonetic">uk-phonetic:" + basic.getString("uk-phonetic") + "</p><br>");
    				JSONArray explains = basic.getJSONArray("explains");
    				for (int i = 0; i < explains.length(); i++) {
    					buffer.append(explains.getString(i) + "<br>");
    				}
    				buffer.append("</body></html>");
    				System.out.println(buffer.toString());
    				//wvShow.loadData(buffer.toString(), "text/html", "UTF-8");
    				//wvShow.getSettings().setDefaultTextEncodingName("UTF-8");
    				wvShow.loadDataWithBaseURL("", buffer.toString(), "text/html", "UTF-8", "");
    			} catch (Exception e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		}
    		else {
    			HtmlString htmlString = new HtmlString();
    			String word = etInput.getText().toString().trim();
    			try {
    				htmlString.setwebString(word, dictName);
    				String html = body + "<div id="" + dictName + "" " +
    						"class="trans-container " + dictName + "">"
    						+htmlString.getwebString() + "</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) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		}
    
    		// 软键盘开启则关闭,关闭则开启
    		imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
    		if (imm.isActive()) {
    			imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,
    					InputMethodManager.HIDE_NOT_ALWAYS);
    		}
    	}
    
    	public void InitViews()  //初始化
    	{
    		btnSrarch = (Button) findViewById(R.id.btnSearch);
    		btnClear = (Button) findViewById(R.id.btnClear);
    		etInput = (EditText) findViewById(R.id.etInput);
    		wvShow = (WebView) findViewById(R.id.wvShow);
    		wvShow.getSettings().setDefaultTextEncodingName("UTF-8");
    		spinner = (Spinner) findViewById(R.id.sp);
    		adapter = new ArrayAdapter<String>(this,
    				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) {
    				// TODO Auto-generated method stub
    				dictName = adapter.getItem(position);
    			}
    
    			@Override
    			public void onNothingSelected(AdapterView<?> parent) {
    				// TODO Auto-generated method stub
    				dictName = dict[0];
    			}
    
    		});
    	}
    
    	public void setListener()  //设置监听器
    	{
    		// 键盘监听
    		etInput.setOnKeyListener(new OnKeyListener() {
    
    			@Override
    			public boolean onKey(View v, int keyCode, KeyEvent event) {
    				// TODO Auto-generated method stub
    				if (keyCode == KeyEvent.KEYCODE_ENTER) {
    					Search();
    					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(MainActivity.this, "查询内容为空",
    							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);
    					Search();
    					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;
    			}
    		}
    	}
    }
    


    效果图


    毕设电子词典效果图


    Keep it simple!
    作者:N3verL4nd
    知识共享,欢迎转载。
  • 相关阅读:
    MSI文件的制作
    QPushButton 响应回车 设置默认按钮
    ubuntu 使用apt-fast 安装软件包
    apt命令集使用教程
    如何在windows下使用git及github仓库管理项目
    如何在windows下使用git及github仓库管理项目
    01. struts2介绍
    人生能跨越多少个年代
    联调踩的坑:空和空字符串引发的巨大差异
    我的亲历:一行代码,百万人民币打水漂
  • 原文地址:https://www.cnblogs.com/lgh1992314/p/5834756.html
Copyright © 2020-2023  润新知