android如何改變editText控制項中部分文字的格式,androidedittext
我們在使用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; } } }