一个简单的中英文翻译词典学习(类似灵格斯)三

      在查询之后的详细信息中,我会注意到在UI开发中关于回车键的实现功能以及在listView中展示所有信息的实现,一个查看单个单词信息怎么实现呢?

 

实现回车键代码功能在Android中的实现

 

 

  /**
    	    * 编辑框添加事件
    	    */
    	   wordEdit.setOnKeyListener(new View.OnKeyListener() {
   			
   			@Override
   			public boolean onKey(View v, int keyCode, KeyEvent event) {
   				if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER){
   					// user input enter
   					queryButton.performClick();
   					return true;
   				}
   				return false;
   			}
   		});

 

在Android中细心童鞋可以发现,Android中可以支持JSON格式的:

  /**
     * 获取查询项的信息
     * @param word
     * @param result
     * @return
     * @throws JSONException
     */
	private List getAudioVoiceByJSON(String word, String result)
			throws JSONException {
		JSONObject jsonObject = new JSONObject(result);
		JSONArray jsonArray = jsonObject.getJSONArray("s");
		if (jsonArray!= null && jsonArray.length() >0){
			List rt = new ArrayList();
			for(int i=0;i 100){
				cache.remove(cache.keySet().iterator().next());
			}
			cache.put(word, rt);
			return rt;
		}
		return Collections.emptyList();
	}

 

实现关闭页面的代码如下:

 /**
   * 点击返回按钮的事件
   */
  backButton.setOnClickListener(new OnClickListener() {
   
   @Override
   public void onClick(View v) {
    finish();
   }
  });

 

 实现界面切换的代码如下:

/**
            *点击一个页面的记录跳转的方法
            */
           searchListView.setOnItemClickListener(new OnItemClickListener() {

   			@Override
   			public void onItemClick(AdapterView arg0, View arg1, int arg2,
   					long arg3) {
   				SearchItem item = searchItemAdapter.getItems().get(arg2);
   				if (item != null){
   					//设置跳转的信息  DictActivity 当前的页面 ,  DetailActivity 单词的详细情况
   					Intent intent = new Intent(DictActivity.this, DetailActivity.class);
   					//设置辅助的信息
   					intent.putExtra("word", item.getWord());
   					//设置激活的界面
   					startActivity(intent);
   				}
   			}
   		});

 

 

 

至于ListView在下一篇Blog中讲解。

(*^__^*) 嘻嘻……

 

 

 

 

源代码如下:

package com.easyway.android.xdict;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
/**
 * 字典首界面
 * @author longgangbai
 * @date 2010-5-28
 * @version 1.0
 * @since JDK6.0
 */
public class DictActivity extends Activity {
    /** Called when the activity is first created. */
    /* (non-Javadoc)
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */
	private ProgressDialog pdialog;
	
	private SearchItemAdapter searchItemAdapter;

	private static final int DIALOG_WORD_REQUIRED = 0;
	
	private  EditText wordEdit;
	private  Button queryButton;
	private  ListView searchListView;
	
	private static Map> cache = new HashMap>();

	/**
	 * 界面启动时使用弹出框
	 */
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_WORD_REQUIRED:
			AlertDialog.Builder builder = new AlertDialog.Builder(
					DictActivity.this);
			builder.setMessage("请输入你想查询的单词!").setCancelable(false)
			.setPositiveButton("确定", new OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.cancel();
							//设置焦点
							wordEdit.setFocusable(true);
						}
					});
			try {
				return builder.create();
			} catch (Exception e) {
				Log.e(DictActivity.class.getName(), e.getMessage(), e);
			}
			break;
		default:
			return super.onCreateDialog(id);
		}
		return super.onCreateDialog(id);
	}
	/**
	 * 调用时启动线程
	 */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置视图
        setContentView(R.layout.main);
        //设置标题
        setTitle("XDict");
        //创建组件
        createComponent();
        
        //绑定事件
        bindListener();
    }
    /**
     * 创建组件
     */
    public void createComponent(){
    	  List items = new ArrayList();
          //创建自定义的ArrayAapter的适配器对象
          searchItemAdapter = new SearchItemAdapter(this, R.layout.row, items);
          //获取ListView对象
          searchListView = (ListView) findViewById(R.id.search_listview);
          //设置适配器对象
          searchListView.setAdapter(searchItemAdapter);

          queryButton = (Button) findViewById(R.id.query_button);
          wordEdit = (EditText) findViewById(R.id.word_edittext);
    }
    /**
     * 绑定事件
     */
    public void bindListener(){
    	   /**
    	    * 编辑框添加事件
    	    */
    	   wordEdit.setOnKeyListener(new View.OnKeyListener() {
   			
   			@Override
   			public boolean onKey(View v, int keyCode, KeyEvent event) {
   				if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER){
   					// user input enter
   					queryButton.performClick();
   					return true;
   				}
   				return false;
   			}
   		});
    	   /**
    	    * 查询按钮添加事件
    	    */
           queryButton.setOnClickListener(new View.OnClickListener() {
   			
   			@Override
   			public void onClick(View v) {
   				searchItemAdapter.getItems().clear();
   				searchItemAdapter.notifyDataSetChanged();
   				String word = wordEdit.getText().toString();
   				if (word == null || word.trim().length() == 0){
   					showDialog(DIALOG_WORD_REQUIRED);
   					return ;
   				}			
   				//添加进度条
   				pdialog = ProgressDialog.show(DictActivity.this, "请稍等...", "正在请求数据...", true);
   				//添加线程的
   				new Thread(){
   					@Override
   					public void run() {

   						final List searchItems = getSearchItems(wordEdit.getText().toString());
   						searchItemAdapter.getItems().addAll(searchItems);
   						//采用UI线程更改界面信息
   						runOnUiThread(new Runnable() {
   							@Override
   							public void run() {
   								searchItemAdapter.notifyDataSetChanged();
   								View noresultTextview = findViewById(R.id.nosearchresult_textview);
   								if (searchItems.isEmpty()){
   									noresultTextview.setVisibility(View.VISIBLE);
   									queryButton.setFocusable(true);
   								}else{
   									noresultTextview.setVisibility(View.INVISIBLE);
   								}
   								//进度条消失
   								pdialog.dismiss();
   							}
   						});
   					}
   				}.start();
   			}
   		});
           /**
            *点击一个页面的记录跳转的方法
            */
           searchListView.setOnItemClickListener(new OnItemClickListener() {

   			@Override
   			public void onItemClick(AdapterView arg0, View arg1, int arg2,
   					long arg3) {
   				SearchItem item = searchItemAdapter.getItems().get(arg2);
   				if (item != null){
   					//设置跳转的信息  DictActivity 当前的页面 ,  DetailActivity 单词的详细情况
   					Intent intent = new Intent(DictActivity.this, DetailActivity.class);
   					//设置辅助的信息
   					intent.putExtra("word", item.getWord());
   					//设置激活的界面
   					startActivity(intent);
   				}
   			}
   		});
    }
    
    /**
     * 设置查询参数
     * @return
     */
    public  Map getDicAppParamsMap(){
    	Map paramsMap=new HashMap();
		paramsMap.put("User-Agent", "Mozilla/5.0 (X11; U; Linux i686; zh-CN; rv:1.9.1.6) Gecko/20091215 Ubuntu/9.10 (karmic) Firefox/3.5.6");
		paramsMap.put("Referer", "http://dict.cn/");
		paramsMap.put("ISAJAX", "yes");
		paramsMap.put("Cookie", "dictid=u; __utma=7761447.596616007.1262230974.1262230974.1262321903.2; __utmz=7761447.1262230974.1.1.utmccn=(direct)|utmcsr=(direct)|utmcmd=(none); h=%2Ffuck%2Fmy%2F%B0%B2%C8%AB%BC%EC%B2%E9%2F%CE%D2%B5%C4%2F%CD%AC%D2%E5%B4%CA%2Fshitwork%2Ffuckhead%2F; __utmc=7761447; __utmb=7761447");
		paramsMap.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
		return  paramsMap;
    }
    
    
    /**
     * 查询相关建议的页面
     * @param word
     * @return
     */
    private List getSearchItems(String word){
    	List cacheData = cache.get(word);
    	if (cacheData != null){
    		return cacheData;
    	}
    	try{
			    String urlString = "http://dict.cn/ajax/suggestion.php?"+"q=" + URLEncoder.encode(word,"utf-8") + "&s=all";
		        Map paramsMap=getDicAppParamsMap();
				String result=HTTPClient.executeByHttpURLConnection(urlString, paramsMap); 
				if (result!=null&&result.length()>0){
					 return getAudioVoiceByJSON(word, result);
				}
		} catch (Exception e) {
			Log.d(DictActivity.class.getName(), "Failed to get the search items", e);
		}
		return Collections.emptyList();
    }
    
    /**
     * 获取查询项的信息
     * @param word
     * @param result
     * @return
     * @throws JSONException
     */
	private List getAudioVoiceByJSON(String word, String result)
			throws JSONException {
		JSONObject jsonObject = new JSONObject(result);
		JSONArray jsonArray = jsonObject.getJSONArray("s");
		if (jsonArray!= null && jsonArray.length() >0){
			List rt = new ArrayList();
			for(int i=0;i 100){
				cache.remove(cache.keySet().iterator().next());
			}
			cache.put(word, rt);
			return rt;
		}
		return Collections.emptyList();
	}
}

 

你可能感兴趣的:(一个简单的中英文翻译词典学习(类似灵格斯)三)