2011-09-06 67 views
3

我正在嘗試爲Android編寫語法突出顯示器。在單獨的AsyncTask線程中運行的突出顯示算法本身效果很好,並返回包含所有必要格式的SpannableString更改文本時停止EditText滾動(Android)

但是,每當我做editText.setText(mySpannableString, BufferType.SPANNABLE)顯示突出顯示的文本EditText滾動回到開始並選擇文本的開始。

顯然,這意味着用戶不能在語法突出顯示器正在處理文本時繼續打字。我怎樣才能阻止呢?有沒有什麼辦法可以在沒有EditText滾動的情況下更新文本?下面是代碼的輪廓:

public class SyntaxHighlighter extends Activity { 

    private EditText textSource; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.editor); 
     textSource = (EditText) findViewById(R.id.codeSource); 
     // Syntax Highlighter loaded text 
     new XMLHighlighter().execute(textSource.getText().toString()); 
    } 

    // Runs on Asyncronous Task 
    private class XMLHighlighter extends AsyncTask<String, Void, SpannableString> { 
     protected SpannableString doInBackground(String... params) { 
      return XMLProcessor.HighlightXML(params[0]); 
     } 
     protected void onPostExecute(SpannableString HighlightedString) { 
      textSource.setText(HighlightedString, BufferType.SPANNABLE); 
     } 
    } 
} 

回答

1

我建議如下:

protected void onPostExecute(SpannableString HighlightedString) { 
    int i = textSource.getSelectionStart(); 
    textSource.setText(HighlightedString, BufferType.SPANNABLE); 
    textSource.setSelection(i); 
} 

光標放回到它的位置,你改變了內容之後。

+2

謝謝,太棒了!只是說,它是textSource.getSelectionStart(),而不是getSelection()。謝謝! – Person

+0

你是對的,我編輯它 – njzk2