[英]Android Edittext : setOnFocusChangeListener doesn't work
[英]How does setOnFocusChangeListener work in Android?
我設計了一個簡單的 Android 應用程序來測試setOnFocusChangeListener
工作原理。
Java 代碼:
public class MainActivity extends AppCompatActivity {
TextView tv;
EditText et;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = findViewById(R.id.textView);
et = findViewById(R.id.edittext);
et.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean b) {
if (b) {
tv.setText("Edit Text is focused!!");
}
else {
tv.setText("You stopped focussing on editText");
}
}
});
}
}
XML 代碼:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Nothing happened"
android:textSize="30sp"
android:gravity="center"
android:id="@+id/textView" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:hint="Write here!!!"
android:id="@+id/edittext" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Click Me!!" />
</LinearLayout>
但是當我點擊編輯文本來寫東西時,編輯文本是重點! 並顯示在文本視圖上。
停止焦點后, EditText
永遠不會顯示在屏幕上,即使我單擊屏幕上的其他任何位置或按鈕也是如此。 我想知道onFocusChange
的else
部分什么時候會顯示?
我想這是因為 editText 永遠不會離開焦點。
在 GUI 編輯器或 XML 上,有一個名為“focusOnTouch”的屬性,editText 視圖默認設置為 true,可以讓您獲得 editText 的焦點,但如果沒有其他視圖將該屬性也設置為 true,則沒有視圖可以獲得焦點。
該屬性存在於每個視圖中,將其設置為 true 對於您要考慮在單擊時獲得焦點的每個視圖,否則,焦點不會傳遞給其他視圖,例如 textView 或按鈕。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.