我正在keyListener上更改EditText的值。

但是,当我更改文本时,光标将移动到EditText的开头。 我需要将光标放在文本的末尾。

如何在EditText中将光标移动到文本的末尾。


#1楼

我认为这可以实现您想要的。

 Editable etext = mSubjectTextEditor.getText();Selection.setSelection(etext, etext.length());

#2楼

您还可以将光标放在EditText视图中文本的末尾,如下所示:

EditText et = (EditText)findViewById(R.id.textview);
int textLength = et.getText().length();
et.setSelection(textLength, textLength);

#3楼

如果您之前调用过setText并且新文本没有得到布局阶段,则在View.post(Runnable)激发的单独可运行对象中调用setSelection (从本主题重新发布)。

因此,对我来说,这段代码有效:

editText.setText("text");
editText.post(new Runnable() {@Overridepublic void run() {registerPhone.setSelection("text".length());}
});

编辑05/16/2019:现在我正在使用Kotlin扩展程序:

fun EditText.placeCursorToEnd() {this.setSelection(this.text.length)
}

然后-editText.placeCursorToEnd()。


#4楼

这是另一种可能的解决方案:

et.append("");

如果由于某种原因它不起作用,请尝试以下解决方案:

et.setSelection(et.getText().length());

#5楼

editText.setOnKeyListener(new View.OnKeyListener() {@Overridepublic boolean onKey(View v, int keyCode, KeyEvent event) {editText.setSelection(editText.getText().length());return false;}
});

#6楼

/*** Set cursor to end of text in edittext when user clicks Next on Keyboard.*/
View.OnFocusChangeListener onFocusChangeListener = new View.OnFocusChangeListener() {@Overridepublic void onFocusChange(View view, boolean b) {if (b) {((EditText) view).setSelection(((EditText) view).getText().length());}}
};mEditFirstName.setOnFocusChangeListener(onFocusChangeListener);
mEditLastName.setOnFocusChangeListener(onFocusChangeListener);

它对我有用!


#7楼

类似于@Anh Duy的答案,但对我没有用。 我还需要仅当用户点击编辑文本时光标才移到末尾,并且之后仍然能够选择光标的位置,这是唯一对我有用的代码

boolean textFocus = false; //define somewhere globally in the class//in onFinishInflate() or somewhere
editText.setOnTouchListener(new OnTouchListener() {@Overridepublic boolean onTouch(View v, MotionEvent event) {editText.onTouchEvent(event);if(!textFocus) {editText.setSelection(editText.getText().length());textFocus = true;}return true;}
});editText.setOnFocusChangeListener(new OnFocusChangeListener() {@Overridepublic void onFocusChange(View v, boolean hasFocus) {textFocus = false;}
});

#8楼

这可以安全地完成技巧:

    editText.setText("");if (!TextUtils.isEmpty(text)) {editText.append(text);}

#9楼

如果您的EditText不清楚:

editText.setText("");
editText.append("New text");

要么

editText.setText(null);
editText.append("New text");

#10楼

如果要选择所有文本,而只输入新文本而不是旧文本,则可以使用

    android:selectAllOnFocus="true"

#11楼

我测试过的所有其他代码均无法正常工作,因为用户仍然可以将插入号/光标放置在字符串中间的任何位置(例如:12 | 3.00-其中|是光标)。 每当在EditText上发生触摸时,我的解决方案始终将光标置于字符串的末尾。

最终的解决方案是:

// For a EditText like:
<EditTextandroid:id="@+id/EditTextAmount"android:layout_height="wrap_content"android:layout_width="fill_parent"android:hint="@string/amount"android:layout_weight="1"android:text="@string/zero_value"android:inputType="text|numberDecimal"android:maxLength="13"/>

@ string / amount =“ 0.00” @ string / zero_value =“ 0.00”

// Create a Static boolean flag
private static boolean returnNext; // Set caret/cursor to the end on focus change
EditTextAmount.setOnFocusChangeListener(new View.OnFocusChangeListener() {@Overridepublic void onFocusChange(View editText, boolean hasFocus) {if(hasFocus){((EditText) editText).setSelection(((EditText) editText).getText().length());}}});// Create a touch listener and put caret to the end (no matter where the user touched in the middle of the string)
EditTextAmount.setOnTouchListener(new View.OnTouchListener() {@Overridepublic boolean onTouch(View editText, MotionEvent event) {((EditText) editText).onTouchEvent(event);((EditText) editText).setSelection(((EditText) editText).getText().length());return true;}});// Implement a Currency Mask with addTextChangedListener
EditTextAmount.addTextChangedListener(new TextWatcher() {@Overridepublic void onTextChanged(CharSequence s, int start, int before, int count) {String input = s.toString();String output = new String();String buffer = new String();String decimals = new String();String numbers = Integer.toString(Integer.parseInt(input.replaceAll("[^0-9]", "")));if(returnNext){returnNext = false;return;}returnNext = true;if (numbers.equals("0")){output += "0.00";}else if (numbers.length() <= 2){output += "0." + String.format("%02d", Integer.parseInt(numbers));}else if(numbers.length() >= 3){decimals = numbers.substring(numbers.length() - 2);int commaCounter = 0;for(int i=numbers.length()-3; i>=0; i--){if(commaCounter == 3){buffer += ",";commaCounter = 0;}buffer += numbers.charAt(i);commaCounter++;}output = new StringBuilder(buffer).reverse().toString() + "." + decimals;}EditTextAmount.setText(output);EditTextAmount.setSelection(EditTextAmount.getText().length());}@Overridepublic void beforeTextChanged(CharSequence s, int start, int count, int after) {/*String input = s.toString();if(input.equals("0.0")){EditTextAmount.setText("0.00");EditTextAmount.setSelection(EditTextAmount.getText().length());return;}*/}@Overridepublic void afterTextChanged(Editable s) {}});

希望能帮助到你!


#12楼

这有效

Editable etext = edittext.getText();
Selection.setSelection(etext,edittext.getText().toString().length());

#13楼

科特林

将光标设置到起始位置

val editText = findViewById(R.id.edittext_id) as EditText
editText.setSelection(0)

将光标设置在EditText末尾

val editText = findViewById(R.id.edittext_id) as EditText
editText.setSelection(editText.getText().length())

下面的代码是将光标放在第二个字符之后:

val editText = findViewById(R.id.edittext_id) as EditText
editText.setSelection(2)

JAVA

将光标设置到起始位置

 EditText editText = (EditText)findViewById(R.id.edittext_id);editText.setSelection(0);

将光标设置在EditText末尾

EditText editText = (EditText)findViewById(R.id.edittext_id);
editText.setSelection(editText.getText().length());

下面的代码是将光标放在第二个字符之后:

EditText editText = (EditText)findViewById(R.id.edittext_id);
editText.setSelection(2);

#14楼

public class CustomEditText extends EditText {public CustomEditText(Context context, AttributeSet attrs) {super(context, attrs);}public CustomEditText(Context context) {super(context);}public CustomEditText(Context context, AttributeSet attrs, int defStyle) {super(context, attrs, defStyle);}@Overrideprotected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {super.onFocusChanged(focused, direction, previouslyFocusedRect);this.setSelection(this.getText().length());}@Overrideprotected void onSelectionChanged(int selStart, int selEnd) {}
}

在XML文件中将此CustomEditText用户使用时,它将起作用。 我已经对此进行了测试,它正在为我工​​作。


#15楼

editText.setSelection是这里的魔力。 基本上,选择可使您将光标放置在所需的任何位置。

EditText editText = findViewById(R.id.editText);
editText.setSelection(editText.getText().length());

这会将光标置于EditText的末尾。 基本上, editText.getText().length()为您提供文本长度。 然后,将setSelection与length一起使用。

editText.setSelection(0);

用于将光标设置在起始位置(0)。


#16楼

你好试试看

 <EditTextandroid:id="@+id/edt_text"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="Hello World!"android:cursorVisible="true"/>

EditText editText = findViewById(R.id.editText); editText.setSelection(editText.getText().length()); // End point EditText editText = findViewById(R.id.editText); editText.setSelection(editText.getText().length()); // End point光标


#17楼

这个问题已经解决了,但是我想如果您想使用新发布的Android数据绑定工具来获得这个答案可能会有用,只需在XML中进行设置即可:

<data><variable name="stringValue" type="String"/>
</data>
...
<EditText...android:text="@={stringValue}"android:selection="@{stringValue.length()}"...
/>

#18楼

就我而言,我创建了以下kotlin分机。 功能,可能对某人有用

 private fun EditText.focus(){requestFocus()setSelection(length())}

然后使用如下

mEditText.focus()

#19楼

如果要将光标放在EditText视图中的文本末尾

 EditText rename;String title = "title_goes_here";int counts = (int) title.length();rename.setSelection(counts);rename.setText(title);

#20楼

EditText editText=findViewById(R.id.et_id);editText.requestFocus();

#21楼

etSSID.setSelection(etSSID.getText().length());

#22楼

对于ViewModel,LiveData和数据绑定

我的笔记应用中需要具有多行支持的EditText此功能。 当用户导航到具有注释文本的片段时,我希望光标位于文本的末尾。

djleop建议的解决方案接近。 但是,这样做的问题是,如果用户将光标放在文本中间的某个位置以进行编辑并开始输入,则光标将再次跳至文本结尾。 发生这种情况是因为LiveData将发出新值,并且光标将再次跳到文本的末尾,导致用户无法在中间的某个位置编辑文本。

为了解决这个问题,我使用MediatorLiveData并使用标志仅将其长度分配为String一次。 这将使LiveData仅读取一次值,即,当用户导航到片段时。 之后,用户可以将光标放置在要在其中编辑文本的任何位置。

视图模型

private var accessedPosition: Boolean = falseval cursorPosition = MediatorLiveData<Event<Int>>().apply {addSource(yourObject) { value ->if(!accessedPosition) {setValue(Event(yourObject.note.length))accessedPosition = true}}
}

在这里, yourObject是从数据库检索的另一个LiveData,其中包含您在EditText中显示的String文本。

然后使用绑定适配器将此MediatorLiveData绑定到您的EditText。

XML格式

使用双向数据绑定来显示文本以及接受文本输入。

<!-- android:text must be placed before cursorPosition otherwise we'll get IndexOutOfBounds exception-->
<EditTextandroid:text="@={viewModel.noteText}"cursorPosition="@{viewModel.cursorPosition}" />

绑定适配器

@BindingAdapter("cursorPosition")
fun bindCursorPosition(editText: EditText, event: Event<Int>?) {event?.getContentIfNotHandled()?.let { editText.setSelection(it) }
}

Event

这里的Event类类似于Google的JoseAlcérreca编写的SingleLiveEvent 。 我在这里使用它来照顾屏幕旋转。 使用单个Event将确保当用户在中间某处编辑文本并且屏幕旋转时,光标不会跳到文本末尾。 屏幕旋转时它将保持相同的位置。

这是Event类:

open class Event<out T>(private val content: T) {var hasBeenHandled = falseprivate set // Allow external read but not write/*** Returns the content and prevents its use again.*/fun getContentIfNotHandled(): T? {return if (hasBeenHandled) {null} else {hasBeenHandled = truecontent}}/*** Returns the content, even if it's already been handled.*/fun peekContent(): T = content
}

这是对我有效的解决方案,并提供了良好的用户体验。 希望它也对您的项目有所帮助。


#23楼

您应该可以使用EditText的方法setSelection()实现此目的,请参见此处


#24楼

尝试这个:

EditText et = (EditText)findViewById(R.id.inbox);
et.setSelection(et.getText().length());

#25楼

ediitext有一个名为append的函数,该函数将字符串值附加到当前edittext值,然后将光标放在该值的末尾。 您可以将字符串值作为当前ediitext值本身,并调用append();。

myedittext.append("current_this_edittext_string");

将光标放在EditText的文本末尾相关推荐

  1. 把光标放在EditText中文本最后

    光标放在EditText中文本最后 editText = (EditText) findViewById(R.id.url_input); editText .setSelection(editTex ...

  2. uniapp光标自动定义到文本框_解决这3个问题,你就敢使用自动编号了

    虽然自动编号在实际工作中很常用的,但还有很多人不敢使用,究其原因就是不知道如何调整编号,本期Word妹与大家分享3个常见的问题. 1.编号与文本间距问题 遇到编号与文本间距太大或者太小,该如何调整呢? ...

  3. C# 文本框定位到文本末尾

    使用ScrollToEnd()方法将文本光标滚动文本末尾. 创建一个简单的WPF App测试该功能. XMAL代码如下: <Grid.ColumnDefinitions> </Gri ...

  4. 将input中的光标移动到文字的末尾后,怎么用js显示光标当前的位置?

    将input中的光标移动到文字的末尾后,怎么用js显示光标当前的位置? 鉴于加深对window.document的理解,写了点东西加深印象 需求: 在点击了编辑之后,直接重置光标的位置和显示光标当前所 ...

  5. linux之用echo输入数据到文本末尾以及用open ssl命令在证书文件里面获取公钥

    1.用echo输入数据到文本末尾 我们知道清空一个文本快速的方法如下 echo "" > file 我们可以用echo输入数字到文本末尾,记住是 >> echo ...

  6. alert获取输入框内容_获取由 AlertDialog 生成的对话框中EditText的文本内容

    在Android开发中,AlertDialog常用于处理用户的登录等.那么如何获取由 AlertDialog 生成的对话框中EditText的文本内容呢? 其实Alertdialog弹出的Activi ...

  7. uniapp光标自动定义到文本框_特检自动化行吊静力检测方案

    主要测量功能使用徕卡测量开发的Windows版数据传输软件,通过蓝牙连接徕卡DISTO,经过简单的测量周期设置,即可实现自动化的距离检测.测量数据还可以输出Excel,甚至可以实时发送至PC运行的第三 ...

  8. html文本框光标位置,html的文本框显示光标 如何在htmlText文本框光标处插入字符...

    HTML 如何设置文本框中光标位置和光标居中 我写样式,把文本框的宽度加大了.但是光标位置在上面. html怎么让文本框的光标出现在内容最后 HTML如何在打开页面时将光标定位在某个文本框 HTML5 ...

  9. 创建一个IntelliJ Idea文件模板,将光标放在文件中的特定位置

    问题: 创建一个IntelliJ文件模板,将光标放在文件中的特定点.实时模板(live template)有$ END $,可在插入实时模板后将光标放在某个位置.那么文件模板呢(file and co ...

最新文章

  1. mac下使用git的冲突的解决方案
  2. 3、Power Map—入门之楼盘分布图
  3. Name Server Daemon (NSD)
  4. ABAP to Json
  5. jmeter更改java内存,jmeter内存溢出解决方法
  6. Redis之主从复制(Sentinel)
  7. (二)使用预定义模型 QStringListModel例子
  8. 用sed替换文件中的空格
  9. python中的__future__模块
  10. pip安装软件报错:Cannot uninstall 'requests'. It is a distutils installed.........
  11. Java服务优雅停机_微服务架构—优雅停机方案
  12. 语音验证码与语音验证码APISDK接口
  13. 奇偶校验c语言ascii,奇偶校验(parity check)
  14. ARPG、MMORPG、MOBA、卡牌类、棋盘类游戏服务器架构图
  15. Android项目:基于安卓Android校园零食配送系统app(计算机毕业设计)
  16. 电子漫画系列更新10张!古老的示波器,USB hub萌妹,超级酷的焊接壁画
  17. 平缓的banner图片切换效果
  18. 卷积层的主要作用_对卷积神经网络CNN的理解,一文读懂卷积神经网络。
  19. 网络安全小白众测如何快速发现安全问题思路
  20. 一些程序员都关注的公众号

热门文章

  1. thinkphp上传
  2. MySQL-5.6.x二进制版本安装记录
  3. hdu 4932 BestCoder Round #4 1002
  4. zepto tap “点透”研究
  5. UPESB天气查询用例(三)
  6. 高效配置Linux代理服务器――Squid
  7. [CB] 支付宝区块链的应用- 区块链发票医保理赔.
  8. 简单poi创建execl
  9. Android 网络HTML查看器
  10. SMB、FTP、DNS、等六个服务总结