35.Android之带删除按钮EditText学习

时间:2023-03-09 00:33:36
35.Android之带删除按钮EditText学习

今天实现Android里自定义带删除功能的EditText,效果如下:

35.Android之带删除按钮EditText学习当输入内容时,EditText变为带有一个删除功能按钮的编辑框,如图:

35.Android之带删除按钮EditText学习

实现代码很简单,直接上代码,

布局文件xml:

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
android:orientation="vertical" > <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/back"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp" > <ImageView
android:id="@+id/search_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="7dp"
android:src="@drawable/search" /> <EditText
android:id="@+id/clearText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@null"
android:hint="搜索"
android:imeOptions="actionDone"
android:singleLine="true" >
</EditText> <Button
android:id="@+id/clear_btn"
android:layout_width="40dp"
android:layout_height="40dp"
android:background="@drawable/clear" />
</LinearLayout> </LinearLayout>

activity代码:

 package com.example.cleartextdemo;

 import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText; public class MainActivity extends Activity { private EditText clearEditText;
private Button clearbtn; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); clearEditText = (EditText) findViewById(R.id.clearText);
clearbtn = (Button) findViewById(R.id.clear_btn);
clearbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
clearEditText.setText("");
}
}); clearEditText.addTextChangedListener(mTextWatcher); } TextWatcher mTextWatcher = new TextWatcher() { @Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub } @Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub } @Override
public void afterTextChanged(Editable s) {
if (clearEditText.getText().toString() != null
&& !clearEditText.getText().toString().equals("")) {
clearbtn.setVisibility(View.VISIBLE);
} else {
clearbtn.setVisibility(View.INVISIBLE);
} } }; }

运行后输入信息如图:

35.Android之带删除按钮EditText学习

按下删除控件变为:

35.Android之带删除按钮EditText学习