学习笔记--EditText点击全选效果

本文介绍了如何在Android中实现EditText点击后全选内容的功能。分别探讨了两种方案:一是通过点击事件,但效果不稳定;二是设置EditText属性,如selectAllOnFocus和singleLine,实现全选并控制焦点变化。
摘要由CSDN通过智能技术生成

需要上,EditText是有内容的,用户点击后就全选,最终达到方便编辑的效果。


方案一:

百度了一下,原来的思路是通过点击事件实现,但是效果很差,有时间点击中间能全选,有时候只是选中光标而已。估计是第一次点击触发touch,第二次点击才触发click.


方案二:

通过EditText的属性,调整焦点,达到全选的效果。同样可以通过setOnTouchListener的代码实现,而touch的UP或者DOWN我自己测试时,都而已实现全选.


代码实现:

editText.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View view, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_UP) {
					editText.setSelectAllOnFocus(true);
					editText.selectAll();
				}
				return false;
			}
		});
xml属性的方式:

  android:selectAllOnFocus="true"
            android:singleLine="true"

        <TextView
            android:id="@+id/edit_1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:focusable="true"
            android:focusableInTouchMode="true"
            android:text="获取焦点" />

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:hint="手机号"
            android:selectAllOnFocus="true"
            android:singleLine="true"
            android:text="123456"
            android:textSize="18sp" />

最后,EditText的处理,都需要取消获取焦点,如果不处理,它会自动获取焦点了


源码一份

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值