当它获得焦点时选择 EditText 中的所有文本而不滚动到末尾

我有一个带有一些预装文本的 EditText。创建EditText时,我想选择所有文本和文本开头的定位。但selectAll()总是转移scrollPosition到最后。

EditText edt;
edt.requestFocus();
edt.selectAll();
edt.scrollTo(0,0); //not scrolling


翻翻过去那场雪
浏览 119回答 1
1回答

牧羊人nacy

参考这个例子:activity_main.xml<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"&nbsp; &nbsp; xmlns:app="http://schemas.android.com/apk/res-auto"&nbsp; &nbsp; xmlns:tools="http://schemas.android.com/tools"&nbsp; &nbsp; android:layout_width="match_parent"&nbsp; &nbsp; android:layout_height="match_parent"&nbsp; &nbsp; android:orientation="vertical"&nbsp; &nbsp; tools:context=".MainActivity">&nbsp; &nbsp; <EditText&nbsp; &nbsp; &nbsp; &nbsp; android:layout_width="match_parent"&nbsp; &nbsp; &nbsp; &nbsp; android:layout_height="wrap_content"&nbsp; &nbsp; &nbsp; &nbsp; android:gravity="top"&nbsp; &nbsp; &nbsp; &nbsp; android:hint="Enter name"&nbsp; &nbsp; &nbsp; &nbsp; android:inputType="textCapSentences|textNoSuggestions|textMultiLine" />&nbsp; &nbsp; <EditText&nbsp; &nbsp; &nbsp; &nbsp; android:id="@+id/etEmail"&nbsp; &nbsp; &nbsp; &nbsp; android:layout_width="match_parent"&nbsp; &nbsp; &nbsp; &nbsp; android:layout_height="wrap_content"&nbsp; &nbsp; &nbsp; &nbsp; android:gravity="top"&nbsp; &nbsp; &nbsp; &nbsp; android:hint="Description"&nbsp; &nbsp; &nbsp; &nbsp; android:inputType="textCapSentences|textNoSuggestions|textMultiLine"&nbsp; &nbsp; &nbsp; &nbsp; android:maxLines="6"&nbsp; &nbsp; &nbsp; &nbsp; android:minLines="3" />&nbsp; &nbsp; <Button&nbsp; &nbsp; &nbsp; &nbsp; android:layout_width="match_parent"&nbsp; &nbsp; &nbsp; &nbsp; android:layout_height="wrap_content"&nbsp; &nbsp; &nbsp; &nbsp; android:onClick="Clickhandle"&nbsp; &nbsp; &nbsp; &nbsp; android:text="Click" /></LinearLayout>MainActivity.javapublic class MainActivity extends AppCompatActivity {&nbsp; &nbsp; EditText editText;&nbsp; &nbsp; @Override&nbsp; &nbsp; protected void onCreate(Bundle savedInstanceState) {&nbsp; &nbsp; &nbsp; &nbsp; super.onCreate(savedInstanceState);&nbsp; &nbsp; &nbsp; &nbsp; setContentView(R.layout.activity_main);&nbsp; &nbsp; &nbsp; &nbsp; editText=findViewById(R.id.etEmail);&nbsp; &nbsp; &nbsp; &nbsp;// editText.setSelectAllOnFocus(true); --> Select all text inside EditText when it gets focus&nbsp; &nbsp; }&nbsp; &nbsp; public void Clickhandle(View view) {&nbsp; &nbsp; &nbsp; &nbsp; editText.requestFocus();&nbsp; &nbsp; &nbsp; &nbsp; editText.selectAll();&nbsp; &nbsp; &nbsp; &nbsp; editText.post(new Runnable() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public void run() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; editText.scrollTo(0, 0);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java