Android EditText常见操作 Android编程之EditText常见操作示例
Jacob-wj 人气:0想了解Android编程之EditText常见操作示例的相关内容吗,Jacob-wj在本文为您仔细讲解Android EditText常见操作 的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Android,EditText,下面大家一起来学习吧。
本文实例讲述了Android编程之EditText常见操作。分享给大家供大家参考,具体如下:
1.获取光标选中的文字
EditText view = (EditText)findViewById(R.id.edt); int start = view.getSelectionStart(); int end = view.getSelectionEnd(); //由于选择的位置和你开始选择文字的顺序有关,所以最好重新判断整理一下顺序,免得出错 if (start>end) { start = start + end ; end = start - end; start = start - end; } String sub = view .getText() .toString().substring(start, end);
2.设置光标在输入框的位置
在编写应用的时候,如果我们要将光标定位到某个位置,可以采用下面的方法:
CharSequence text = editText.getText(); //Debug.asserts(text instanceof Spannable); if (text instanceof Spannable) { Spannable spanText = (Spannable)text; Selection.setSelection(spanText, text.length()); }
其中的代码text.length()
为你想要设置的位置,此处是设置到文本末尾。
3 在指定位置插入字符串
public class EditTextCopyActivity extends Activity { /** Called when the activity is first created. */ private EditText et1 ,et2,et3,et4,et5,et6,et7; private Button bt1,bt2,bt3; private ClipboardManager clip ; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); initViews(); bt1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { View view = getCurrentFocus(); if (view instanceof EditText) { EditText et = (EditText)view; int start = et.getSelectionStart(); int end = et.getSelectionEnd(); if (start>end) { start = start + end ; end = start - end; start = start - end; } String sub = et.getText().toString().substring(start, end); clip.setText(sub); } } }); bt2.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { View view = getCurrentFocus(); if (view instanceof EditText) { EditText et = (EditText)view; int start = et.getSelectionStart(); System.out.println(start+"--------------"); String s = clip.getText().toString(); et.getText().insert(start,s); } } }); bt3.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { View view = getCurrentFocus(); if (view instanceof EditText) { EditText et = (EditText)view; int start = et.getSelectionStart(); int end = et.getSelectionEnd(); if (start>end) { start = start + end ; end = start - end; start = start - end; } String sub = et.getText().toString().substring(start, end); et.getText().delete(start, end); clip.setText(sub); } } }); } private void initViews(){ et1 = (EditText)this.findViewById(R.id.editText1); et2 =(EditText)this.findViewById(R.id.editText2); et3 =(EditText)this.findViewById(R.id.editText3); et4 =(EditText)this.findViewById(R.id.editText4); et5 =(EditText)this.findViewById(R.id.editText5); et6 =(EditText)this.findViewById(R.id.editText6); clip = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE); bt1=(Button)this.findViewById(R.id.button1); bt2 = (Button)this.findViewById(R.id.button2); bt3 = (Button)this.findViewById(R.id.button3); } }
希望本文所述对大家Android程序设计有所帮助。
加载全部内容