android输入法02:openwnn源码解析03—CandidatesView

本文是介绍openwnn源码的第三篇,将要介绍的内容是日文输入法的CandidatesView。

1、相关功能

        为了介绍源码,当然需要介绍一下这个CandidatesView的样式及功能。由于我没有去编译openwnn源码,因此只能以android模拟器自带的openwnn日文输入法(japanese ime)来介绍。具体功能根据我对该输入法的使用和对openwnn源码的阅读,应该是没有多大差别的。(android2.2的模拟器)

       首先来看一下功能截图:


        第一张是输入あ的候选框图,第二张是点击第一张那个向上箭头后的候选框图。也就是说,第一张只是显示了部分候选词,第二张则是显示了所有的候选词,同时如果满屏都无法显示所有的候选词,则还有一个滚动条。

        如果你单击某一个候选词,则该候选词上屏。若你长按一个候选词,则候选词会变为如下格式:


       点击关闭,则恢复到长按以前的状态,若点选择,则该候选词上屏。

2 CandidatesViewManager

       在源码中,涉及到CandidatesView的只有两个类:CandidatesViewManager.java和TextCandidatesViewManager.java。前者是通用接口,后者是具体的是实现类。这里你会发现不管哪种语言,使用的都是这两个类,并没有对TextCandidatesViewManager类进行继承。说明这个设计还是比较好(或者会不会CandidatesView本身就比较简单)。

       首先我们来看一下CandidatesViewManager.java,这是一个接口类。输入法只要使用这个接口就可以了,并不需要关注其实现细节。其代码比较简答,如下所示:

[java]  view plain copy
  1. /** 
  2.  * The interface of candidates view manager used by {@link OpenWnn}. 
  3.  * 
  4.  * @author Copyright (C) 2008, 2009 OMRON SOFTWARE CO., LTD.  All Rights Reserved. 
  5.  */  
  6. public interface CandidatesViewManager {  
  7.     /** Size of candidates view (normal) */  
  8.     public static final int VIEW_TYPE_NORMAL = 0;  
  9.     /** Size of candidates view (full) */  
  10.     public static final int VIEW_TYPE_FULL   = 1;  
  11.     /** Size of candidates view (close/non-display) */  
  12.     public static final int VIEW_TYPE_CLOSE  = 2;  
  13.   
  14.     /** 
  15.      * Attribute of a word (no attribute) 
  16.      * @see jp.co.omronsoft.openwnn.WnnWord 
  17.      */  
  18.     public static final int ATTRIBUTE_NONE    = 0;  
  19.     /** 
  20.      * Attribute of a word (a candidate in the history list) 
  21.      * @see jp.co.omronsoft.openwnn.WnnWord 
  22.      */  
  23.     public static final int ATTRIBUTE_HISTORY = 1;  
  24.     /** 
  25.      * Attribute of a word (the best candidate) 
  26.      * @see jp.co.omronsoft.openwnn.WnnWord 
  27.      */  
  28.     public static final int ATTRIBUTE_BEST    = 2;  
  29.     /** 
  30.      * Attribute of a word (auto generated/not in the dictionary) 
  31.      * @see jp.co.omronsoft.openwnn.WnnWord 
  32.      */  
  33.     public static final int ATTRIBUTE_AUTO_GENERATED  = 4;  
  34.   
  35.     /** 
  36.      * Initialize the candidates view. 
  37.      * 
  38.      * @param parent    The OpenWnn object 
  39.      * @param width     The width of the display 
  40.      * @param height    The height of the display 
  41.      * 
  42.      * @return The candidates view created in the initialize process; {@code null} if cannot create a candidates view. 
  43.      */  
  44.     public View initView(OpenWnn parent, int width, int height);  
  45.   
  46.     /** 
  47.      * Get the candidates view being used currently. 
  48.      * 
  49.      * @return The candidates view; {@code null} if no candidates view is used currently. 
  50.      */  
  51.     public View getCurrentView();  
  52.   
  53.     /** 
  54.      * Set the candidates view type. 
  55.      * 
  56.      * @param type  The candidate view type 
  57.      */  
  58.     public void setViewType(int type);  
  59.   
  60.     /** 
  61.      * Get the candidates view type. 
  62.      * 
  63.      * @return      The view type 
  64.      */  
  65.     public int getViewType();  
  66.   
  67.     /** 
  68.      * Display candidates. 
  69.      * 
  70.      * @param converter  The {@link WnnEngine} from which {@link CandidatesViewManager} gets the candidates 
  71.      * 
  72.      * @see jp.co.omronsoft.openwnn.WnnEngine#getNextCandidate 
  73.      */  
  74.     public void displayCandidates(WnnEngine converter);  
  75.   
  76.     /** 
  77.      * Clear and hide the candidates view. 
  78.      */  
  79.     public void clearCandidates();  
  80.   
  81.     /** 
  82.      * Reflect the preferences in the candidates view. 
  83.      * 
  84.      * @param pref    The preferences 
  85.      */  
  86.     public void setPreferences(SharedPreferences pref);  
  87. }  
        首先它定义了候选词列表的三种状态:普通、全屏、关闭。这个大家看第第1部分那两张图就明白了。

       另外它还定义后了候选词的属性,这些词有4种属性,具体看英文注释。

        大家比较关注的应该是它提供给输入法使用的接口,可以看出需要提供给外界使用的接口是比较少的。

3 TextCandidatesViewManager

         这一部分是CandidatesView的具体实现类。我们直观上看CandidatesView主要的功能应该是获得并显示候选词,并做一些功能方便用户使用。因此我们按照CandidatesViewManager类中的接口来介绍一下其实现方式。

3.1 initView

        这一部分初始化CandidatesView。其代码如下:

[java]  view plain copy
  1. /** @see CandidatesViewManager */  
  2.     public View initView(OpenWnn parent, int width, int height) {  
  3.         mWnn = parent;  
  4.         mViewWidth = width;  
  5.   
  6.         mSelectBottonText =  mWnn.getResources().getString(R.string.button_candidate_select);  
  7.         mCancelBottonText = mWnn.getResources().getString(R.string.button_candidate_cancel);  
  8.   
  9.         mViewBody = (ViewGroup)parent.getLayoutInflater().inflate(R.layout.candidates, null);  
  10.   
  11.         mViewBodyScroll = (ScrollView)mViewBody.findViewById(R.id.candview_scroll);  
  12.         mViewBodyScroll.setOnTouchListener(this);  
  13.   
  14.         mViewBodyText = (EditText)mViewBody.findViewById(R.id.text_candidates_view);  
  15.         mViewBodyText.setOnTouchListener(this);  
  16.         mViewBodyText.setTextSize(18.0f);  
  17.         mViewBodyText.setLineSpacing(6.0f, 1.5f);  
  18.         mViewBodyText.setIncludeFontPadding(false);  
  19.         mViewBodyText.setFocusable(true);  
  20.         mViewBodyText.setCursorVisible(false);  
  21.         mViewBodyText.setGravity(Gravity.TOP);  
  22.           
  23.         mReadMoreText = (TextView)mViewBody.findViewById(R.id.read_more_text);  
  24.         mReadMoreText.setText(mWnn.getResources().getString(R.string.read_more));  
  25.         mReadMoreText.setTextSize(24.0f);  
  26.   
  27.         mPortrait = (height > 450)? true : false;  
  28.         setViewType(CandidatesViewManager.VIEW_TYPE_CLOSE);  
  29.   
  30.         mGestureDetector = new GestureDetector(this);  
  31.         return mViewBody;  
  32.     }  
        这里我们看到CandidatesView显示的view主要有三个:mViewBodyText,mReadMoreText,mViewBodyScroll 。mViewBodyText是个EditText,我们看到的候选词列表由它显示;mReadMoreText是一个TextView,就是一个“more”按钮,点击可以查看更多的候选词。另外mSelectBottonText,mCancelBottonText 这两个是按钮来着,用于长按一个候选词时弹出的对话框。

        这里主要是设置一些参数,大家具体看代码了。

3.2 setViewType

        这一步主要是设置CandidatesView的状态,候选词列表的三种状态:普通、全屏、关闭。在上面初始化view的时候是将其设置为关闭状态。这一部分的代码:

[java]  view plain copy
  1. /** @see CandidatesViewManager#setViewType */  
  2.    public void setViewType(int type) {  
  3.        boolean readMore = setViewLayout(type);  
  4.        addNewlineIfNecessary();  
  5.   
  6.        if (readMore) {  
  7.            displayCandidates(this.mConverter, false, -1);  
  8.        } else {   
  9.         if (type == CandidatesViewManager.VIEW_TYPE_NORMAL) {  
  10.                mIsFullView = false;  
  11.             if (mDisplayEndOffset > 0) {  
  12.                    int maxLine = getMaxLine();  
  13.                    displayCandidates(this.mConverter, false, maxLine);  
  14.                 } else {  
  15.                     setReadMore();  
  16.                 }  
  17.             }  
  18.        }  
  19.    }  
        这一步主要是设置CandidatesView的状态,同时根据其状态显示候选词(其中调用了显示候选词函数displayCandidates)。设置状态的主要函数在setViewLayout,这个主要是设置显示的行数等等信息。而其中addNewlineIfNecessary函数的作用则是,修改了CandidatesView的状态以后,候选词的数量可能比较少,这时候需要将空余部分显示为空行。

3.3 displayCandidates

       这个函数是这里面最重要的函数,其功能是根据候选词引擎获得候选词,同时显示候选词。这个函数是经过重载的,它由两个形式:

[java]  view plain copy
  1. /** @see CandidatesViewManager#displayCandidates */  
  2. public void displayCandidates(WnnEngine converter) {  
  3.     mCanReadMore = false;  
  4.     mDisplayEndOffset = 0;  
  5.     mIsFullView = false;  
  6.     int maxLine = getMaxLine();  
  7.     displayCandidates(converter, true, maxLine);  
  8. }  
[java]  view plain copy
  1. /** 
  2.      * Display the candidates. 
  3.      *  
  4.      * @param converter  {@link WnnEngine} which holds candidates. 
  5.      * @param dispFirst  Whether it is the first time displaying the candidates 
  6.      * @param maxLine    The maximum number of displaying lines 
  7.      */  
  8.     synchronized private void displayCandidates(WnnEngine converter, boolean dispFirst, int maxLine) {  
        这里前者是对外接口,后者则是私有函数。注意这里有一个synchronized关键字,我猜测是用于保护显示,也就是前一次CandidatesView显示完成以后,才可以进行后一次显示,这样就不会错乱。这在快速输入的时候是比较有用的。

        对于displayCandidates函数的具体实现,由于我没有很详细的去看,所以无法讲。但是根据大概的了解,我猜测是这样的:首先初始化;获得下一个候选词同时生成该候选词的显示信息(比如一个很长的候选词可能需要分在多行显示)。

3.3.1 createDisplayText

        这里获得下一个候选词并生成该候选词的显示信息主要由createDisplayText函数完成的。该函数源码如下:

[java]  view plain copy
  1. /** 
  2.      * Create the string to show in the candidate window. 
  3.      * 
  4.      * @param word      A candidate word 
  5.      * @param maxLine   The maximum number of line in the candidate window 
  6.      * @return      The string to show 
  7.      */  
  8.     private StringBuffer createDisplayText(WnnWord word, int maxLine) {  
  9.         StringBuffer tmp = new StringBuffer();  
  10.         int padding = ViewConfiguration.getScrollBarSize() +   
  11.                       mViewBodyText.getPaddingLeft() +         
  12.                       mViewBodyText.getPaddingRight();         
  13.         int width = mViewWidth - padding;  
  14.         TextPaint p = mViewBodyText.getPaint();  
  15.         float newLineLength = measureText(p, word.candidate, 0, word.candidate.length());  
  16.         float separatorLength = measureText(p, CANDIDATE_SEPARATOR, 0, CANDIDATE_SEPARATOR.length());  
  17.         boolean isFirstWordOfLine = (mLineLength == 0);//mLineLength记录的是一行的长度  
  18.   
  19.         int maxWidth = 0;  
  20.         int lineLength = 0;  
  21.         lineLength += newLineLength;  
  22.          
  23.         maxWidth += width - separatorLength;  
  24.           
  25.         mLineLength += newLineLength;  
  26.         mLineLength += separatorLength;  
  27.         mLineWordCount++;  
  28.   
  29.          
  30.         if (mLineWordCount == 0) {  
  31.             mLineLength = lineLength;  
  32.             mLineLength += separatorLength;  
  33.         }  
  34.           
  35.         if (!isFirstWordOfLine && (width < mLineLength) && mLineWordCount != 0) {  
  36.             tmp.append("\n");   //此时说明如果将word放入这一行,则这一行就会太长了,因此需要将word放入下一行  
  37.             mLineLength = lineLength;  
  38.             mLineLength += separatorLength;  
  39.             mLineWordCount = 0;  
  40.         }  
  41.         return adjustDisplaySize(word, tmp, lineLength, maxWidth, maxLine);  
  42.     }  

        这里最重要的就是根据该候选词的长度来生成候选词列表的显示信息,也就是说该候选词是否在下一行显示或者分多行显示等。其中还调用了一个adjustDisplaySize。这个函数从函数名就可以猜出大概了。

3.3.2 countLineUsingMeasureText

        这个函数的作用是利用需要输出的字符串,来计算需要多少行来显示。这其中涉及几个部分:1、跟字体大小有关;2、跟候选词间隔有关;3、跟候选框与屏幕左右边的间隔有关;4、跟滚动条的宽度有关;5、当然跟屏幕大小等有关系了。程序大概是利用这些信息来计算CandidatesView展示这些候选词需要多少行来显示。其代码如下:

[java]  view plain copy
  1. /** 
  2.     * Count lines using {@link Paint#measureText}. 
  3.     * 
  4.     * @param text       The text to display 
  5.     * @return       Number of lines 
  6.     */  
  7.    private int countLineUsingMeasureText(CharSequence text) {  
  8.        StringBuffer tmpText = new StringBuffer(text);  
  9.        mStartPositionArray.add(mWordCount,tmpText.length());  
  10.        int padding =  
  11.            ViewConfiguration.getScrollBarSize() +  
  12.            mViewBodyText.getPaddingLeft() +         
  13.            mViewBodyText.getPaddingRight();         
  14.        TextPaint p = mViewBodyText.getPaint();  
  15.        int lineCount = 1;  
  16.        int start = 0;  
  17.        for (int i = 0; i < mWordCount; i++) {  
  18.            if (tmpText.length() < start ||  
  19.                tmpText.length() < mStartPositionArray.get(i + 1)) {  
  20.                return 1;  
  21.            }  
  22.            float lineLength = measureText(p, tmpText, start, mStartPositionArray.get(i + 1));  
  23.            if (lineLength > (mViewWidth - padding)) {  
  24.                lineCount++;  
  25.                start = mStartPositionArray.get(i);  
  26.                i--;  
  27.            }  
  28.        }  
  29.        return lineCount;  
  30.    }  
        这里实际上就是获得每一个候选词,判断如果将该候选词放入当前行,看当前行是否大于(mViewWidth - padding)。如果大于,则说明当前行已经放不下该候选词了,需要另起一行;若是不大于,则说明当前可以放得下该候选词,于是继续选取下一个候选词看是否可以放入当前行。

        另外,这里讲一下导入openwnn源码时,measureText是有错的。因为它导入的是android.text.styled类(至少在2.1以后的android代码中已经找不到android.text.styled了)。正确的方法是,将import  android.text.styled这一句删除,同时measureText函数修改为如下形式:

[java]  view plain copy
  1. public int measureText(TextPaint paint, CharSequence text, int start, int end) {  
  2.         return (int)paint.measureText(text, start, end);  
  3.     }  


3.4 用户操作处理

       另外这个类有很大一部分篇幅是用来处理用户操作的,比如选择候选词。我们来回顾下该类的申明

[java]  view plain copy
  1. public class TextCandidatesViewManager implements CandidatesViewManager, OnTouchListener,  
  2.                                                          GestureDetector.OnGestureListener  
        从这里也可以看出,该类不仅可以处理触摸操作也可以处理用户手势。

       对于用户操作,我想最简单的莫过于用户点击某个候选词然后该候选词上屏。这里,我想大家可以想到一个问题,就是用户点击的是屏幕上的某一点,系统怎么知道所选择的哪个候选词并将该候选词上屏呢?这里就会有一个将坐标转化为候选词的操作:

[java]  view plain copy
  1. /** 
  2.      * Convert a coordinate into the offset of character 
  3.      * 
  4.      * @param x     The horizontal position 
  5.      * @param y     The vertical position 
  6.      * @return  The offset of character 
  7.      */  
  8.     public int getOffset(int x,int y){  
  9.         Layout layout = mViewBodyText.getLayout();  
  10.         int line = layout.getLineForVertical(y);  
  11.           
  12.         if( y >= layout.getLineTop(line+1) ){  
  13.             return layout.getText().length();  
  14.         }  
  15.   
  16.         int offset = layout.getOffsetForHorizontal(line,x);  
  17.         offset -= TOUCH_ADJUSTED_VALUE;  
  18.         if (offset < 0) {  
  19.             offset = 0;  
  20.         }  
  21.         return offset;  
  22.     }  

        这里主要是通过坐标获得某个候选词的偏移量,而该偏移量是在mPositionToWordIndexArray中定义的。对于mPositionToWordIndexArray中值的确定,我们可以在displayCandidates函数中看到:

[java]  view plain copy
  1. /* save the candidate string */  
  2.         mCandidates.delete(0, mCandidates.length());  
  3.         mCandidates.append(tmp);  
  4.         int j = 0;  
  5.         for (int i = 0; i < mWordCount; i++) {  
  6.             while (j <= mEndPositionArray.get(i)) {  
  7.                 if (j < mStartPositionArray.get(i)) {  
  8.                     mPositionToWordIndexArray.add(j,-1);  
  9.                 } else {  
  10.                     mPositionToWordIndexArray.add(j,i);  
  11.                 }  
  12.                 j++;  
  13.             }  
  14.             mPositionToWordIndexArray.add(j,-1);      
  15.             mPositionToWordIndexArray.add(j + 1,-1);  
  16.         }  
        这段代码,我猜测是将每一个偏移位置所对应的候选词编号都记录下来。因此你获得一个便宜位置就可以通过查询mPositionToWordIndexArray这个数组来找到其所对应的候选词编号。

         于是,用户如果按住某个候选词时,会调用如下函数:

[java]  view plain copy
  1. /** from GestureDetector.OnGestureListener class */  
  2.     public boolean onDown(MotionEvent arg0) {  
  3.         if (!mCandidateDeleteState) {  
  4.             int position = getOffset((int)arg0.getX(),(int)arg0.getY());  
  5.             int wordIndex = mPositionToWordIndexArray.get(position);  
  6.             if (wordIndex != -1) {  
  7.                 int startPosition = mStartPositionArray.get(wordIndex);  
  8.                 int endPosition = 0;  
  9.                 if (mDisplayEndOffset > 0 && getViewType() == CandidatesViewManager.VIEW_TYPE_NORMAL) {  
  10.                     endPosition = mDisplayEndOffset + CANDIDATE_SEPARATOR.length();  
  11.                 } else {  
  12.                     endPosition = mEndPositionArray.get(wordIndex);  
  13.                 }  
  14.                 mViewBodyText.setSelection(startPosition, endPosition);  
  15.                 mViewBodyText.setCursorVisible(true);  
  16.                 mViewBodyText.invalidate();  
  17.                 mHasStartedSelect = true;  
  18.             }  
  19.         }  
  20.         return true;  
  21.     }  
        这里也就可以看上上面那个求偏移量的函数是怎么用的。

4、其他

        本文主要是对CandidatesView的形成过程做了一个大概的介绍。但是由于时间和能力有限,对如下几个问题未能深入,后续有时间会补上。

1)displayCandidates的具体实现细节

2)我一直有个疑问,显示候选词的既然是一个EditText,那作为一个编辑框,为什么我可以显示一个候选词列表,而且可以点击?

3)用户手势操作的具体分析

        第2)问题,估计解决第1)个问题后就可以解决了。第3)问题,其实没有太大所谓。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值