软件编程
位置:首页>> 软件编程>> Android编程>> android如何改变editText控件中部分文字的格式

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

作者:ganchuanpu  发布时间:2023-08-24 18:58:36 

标签:android,edittext

我们在使用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;
 }
}
}

来源:http://www.cnblogs.com/ganchuanpu/p/6505983.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com