您的位置:首页 > 移动开发 > Android开发

android如何改变editText控件中部分文字的格式

2017-03-06 08:40 489 查看

我们在使用editText控件的时候,会遇到这样的一问题,就是我在输入时候,当我选择让文字变粗时,我输入的文字就会变粗,当我去掉选择时,再输入文字时,文字就是正常情况了。

这种情况,大家一般认为很简单啊。editText中不是有setTypeface这个方法吗。只要使用edit_temp.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));就可以了。可是问题来了。这种方法,是将editText中所有的文字的格式全变了。可是我想要的格式是这样的:  正常格式变粗的格式正常的格式

public class FragmentAddNote extends Fragment implements OnClickListener {
//定义输入文本控件
private EditText edit_temp;
//定义屏幕下面菜单栏--字体变粗按钮
private LinearLayout linearLayout_Bold;
private ImageView img_Bold;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main_addnote, container, false);
initView(view);
return view;
}
public void initView(View view)
{
//初始化屏幕下面菜单栏--字体变粗按钮
linearLayout_Bold = (LinearLayout)view.findViewById(R.id.linearLayout_Bold);
linearLayout_Bold.setOnClickListener(this);
img_Bold = (ImageView)view.findViewById(R.id.img_Bold);
//初始化输入文本控件
edit_temp = (EditText)view.findViewById(R.id.edit_temp);
edit_temp.addTextChangedListener(new editTextChangedListener());
}
class editTextChangedListener implements TextWatcher{
//定义当前输入的字符数
private int CharCount = 0;
//s:变化后的所有字符
public void afterTextChanged(Editable s) {
//将光标点,移动到最后一个字
edit_temp.setSelection(s.length());
}
//s:变化前的所有字符; start:字符开始的位置; count:变化前的总字节数;after:变化后的字节数
public void beforeTextChanged(CharSequence s, int start, int count,int after) {
}
//S:变化后的所有字符;start:字符起始的位置;before: 变化之前的总字节数;count:变化后的字节数
public void onTextChanged(CharSequence s, int start, int before, int count) {
//判断当前输入的字符数,与文本框内的字符数长度是否一样,如果一样,则不进行操作
//主要用来跳出循环,当改变文字时,onTextChanged就认为有所变化,会进入死循环,所以采用这种方式结束循环
if(CharCount!=edit_temp.length())
{
//将当前字符串的长度给输入字符串变量
CharCount = edit_temp.length();
//定义SpannableString,它主要的用途就是可以改变editText,TextView中部分文字的格式,以及向其中插入图片等功能
SpannableString ss = new SpannableString(s);
if(linearLayout_Bold.getTag().toString().equals("1"))
{
ss.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), start, s.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
edit_temp.setText(ss);
}
}
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.linearLayout_Bold:
if(linearLayout_Bold.getTag().toString().equals("0"))
{
img_Bold.setImageResource(R.drawable.ic_editor_bar_rtf_bold_on);
linearLayout_Bold.setTag("1");
//edit_temp.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
}else if(linearLayout_Bold.getTag().toString().equals("1"))
{
img_Bold.setImageResource(R.drawable.ic_editor_bar_rtf_bold);
linearLayout_Bold.setTag("0");
//edit_temp.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
}
break;
default:
break;
}
}
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持脚本之家!

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android edittext