Android开发中,使用 EditText 输入内容,如何进行一键清空内容处理


本文仅为个人的处理方式,希望能对您有所帮助,欢迎各位留言指正,抱拳了

1、text.xml示例:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ccc"> <EditText android:id="@+id/input" android:layout_width="@dimen/dimen_270" android:layout_height="wrap_content" android:maxLines="1" android:hint="请输入内容" android:textSize="@dimen/dimen_16" android:textColor="@color/color_fff" android:layout_marginTop="@dimen/dimen_10" /> <ImageView android:id="@+id/del" android:layout_width="@dimen/dimen_14" android:layout_height="@dimen/dimen_14" android:visibility="gone" android:layout_marginTop="@dimen/dimen_28" android:src="@mipmap/bonus_envelope_cancel_icon_normal" android:layout_toRightOf="@id/input"/> </RelativeLayout> 

 

2.textActivity.java示例:
public class textActivity extends Activity implements View.OnClickListener { private EditText input; private ImageView inputDel; //实例化一键清除输入内容 @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.text); initView(); initListener(); } //对变量进行初始化 private void initView(){ inputDel = findViewById(R.id.del); input = findViewById(R.id.input); } //设置监听器 private void initListener(){ input.addTextChangedListener(textWatcher); inputDel.setOnClickListener(this); } private TextWatcher textWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { if (input.getEditableText().length() >= 1){ inputDel.setVisibility(View.VISIBLE); } else{ inputDel.setVisibility(View.GONE); } } }; //点击事件(清空) @Override public void onClick(View v) { switch (v.getId()){ case R.id.del: input.setText(""); break; } } } 

 

3、在AndroidManifest.xml中进行注册:
<activity android:name=".textActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> 

 

4、效果图如下:

在这里插入图片描述

在这里插入图片描述

动图展示:
在这里插入图片描述


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM