我想以EditText
粗体设置所选文字。
我已经可以找到我选择的字符,并getSelectionStart() and getSelectionEnd( )
我知道位置在哪里。
但我的问题是,我想用Button设置所选的Text粗体,并且不知道如何用String设置粗体字体(我只知道如何用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 :(得分:1)
使用SpannableStringBuilder。
SpannableStringBuilder stringBuilder = (SpannableStringBuilder) fullscreeneditText.getText();
stringBuilder.setSpan(new StyleSpan(Typeface.BOLD), selectionStart, selectionEnd, 0);
请注意,如果您想多次执行此操作,则应首先删除原始范围。
答案 1 :(得分:0)
使用Editext
fullscreenEdittext.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));
答案 2 :(得分: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));