2014-09-01 135 views
1

我想以粗体EditText设置选定的文本。如何将选定的文字设置为粗体?

已经有可能找出我选择的字符并用getSelectionStart() and getSelectionEnd()我知道位置在哪里。

但我的问题是,我想用按钮设置选定的文本粗体,不知道如何设置字符粗体与字符串(我只知道如何设置它与EditText)。

因此,这里是我的示例代码:

fettdruckButton.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 

      int selectionStart = fullscreenEdittext.getSelectionStart(); 
      int selectionEnd = fullscreenEdittext.getSelectionEnd(); 

      int differenz = selectionEnd - selectionStart; 

      String selectedText = fullscreenEdittext.getText().toString().substring(selectionStart, selectionEnd); 
      Log.d("selectedText", "selectedText " + selectedText + "|" + selectionStart + "|" + selectionEnd); 


      //fullscreenEdittext.setTypeface(null, Typeface.BOLD); 

     } 
    }); 
+0

ü想要它在点击按钮后或选择文本时点击 – 2014-09-01 08:36:55

+0

按钮之后点击所选文本应显示为粗体 – user3603935 2014-09-01 08:38:32

回答

0

使用的EditextfullscreenEdittext.setText(Html.fromHtml(styledText)); 使用HTML格式的标签<b>selectedText</b>的属性,以使选定的文本加粗。 请各位看看下面的代码片断

int selectionStart = fullscreenEdittext.getSelectionStart(); 
    int selectionEnd = fullscreenEdittext.getSelectionEnd(); 

    String startingText = fullscreenEdittext.getText().toString() 
      .substring(0, selectionStart); 
    String selectedText = fullscreenEdittext.getText().toString() 
      .substring(selectionStart, selectionEnd); 
    String endingText = fullscreenEdittext.getText().toString() 
      .substring(selectionEnd); 

    fullscreenEdittext.setText(Html.fromHtml(startingText + "<b>" 
      + selectedText + "</b>" + endingText)); 
0
String completetext=fullscreenEdittext.getText().toString(); 
int selectionStart = fullscreenEdittext.getSelectionStart(); 
int selectionEnd = fullscreenEdittext.getSelectionEnd(); 
int differenz = selectionEnd - selectionStart; 
String selectedText = fullscreenEdittext.getText().toString().substring(selectionStart, selectionEnd); 
Log.d("selectedText", "selectedText " + selectedText + "|" + selectionStart + "|" + selectionEnd); 

String part1=fullscreenEdittext.getText().toString().substring(0, selectionStart); 

String part2=fullscreenEdittext.getText().toString().substring(selectionStart, selectionEnd); 

String part3=fullscreenEdittext.getText().toString().substring(selectionEnd,completetext.length()); 

fullscreenEdittext.setText(Html.fromHtml(part1+"<b>" + part2+ "</b>" +part3)); 
1

使用SpannableStringBuilder。

SpannableStringBuilder stringBuilder = (SpannableStringBuilder) fullscreeneditText.getText(); 
stringBuilder.setSpan(new StyleSpan(Typeface.BOLD), selectionStart, selectionEnd, 0); 

请注意,如果您想多次执行此操作,应先删除原始范围。

相关问题