Android控件系列之EditText使用方法

  //表示文本框是否为空

  private Boolean isEmpty = true;

  /** Called when the activity is first created. */

  @Override

  public void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setContentView(R.layout.main);

  EditText et = (EditText)this.findViewById(R.id.et);

  //监听控件的焦点改变事件

  et.setOnFocusChangeListener(new OnFocusChangeListener() {

  @Override

  public void onFocusChange(View arg0, boolean arg1) {

  // TODO Auto-generated method stub

  //获取触发事件的EditText

  EditText clickEditText = (EditText)arg0;

  //如果失去焦点

  if(arg1 == false)

  {

  //获取当前文本

  String text =clickEditText.getText().toString().trim();

  //如果的确人为输入过内容

  if(text.length()>0

  &text.equals("请输入您的名字")== false)

  {

  isEmpty = false;

  clickEditText.setTextColor(Color.BLACK);

  clickEditText.setText(text);

  }

  else

  {

  clickEditText.setText("请输入您的名字");

  clickEditText.setTextColor(Color.GRAY);

  isEmpty = true;

  }

  }

  //如果获得焦点

  else

  {

  clickEditText.setTextColor(Color.BLACK);

  //如果处于未编辑状态,则清空“请输入您的名字”这几个字

  if(isEmpty == true)

  {

  clickEditText.setText("");

  }

  }

  }

  });

  //监听控件有新字符输入

  et.setOnKeyListener(new OnKeyListener() {

  @Override

  public boolean onKey(View arg0, int arg1, KeyEvent arg2) {

  // TODO Auto-generated method stub

  //获取触发事件的EditText

  EditText clickEditText = (EditText)arg0;

  //获取当前文本

  String text =clickEditText.getText().toString().trim();

  if(text.length()==10)

  {

  //提示用户

  Toast toast = Toast.makeText(MyActivity.this, "最大长度为10个字符", Toast.LENGTH_SHORT);

  toast.setGravity(0, 0, 0);

  toast.show();

  }

  return false;

  }

  });

  }