OpenHarmony中的EditText是一個用于顯示和編輯單行文本的組件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:h="http://schemas.huawei.com/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"
android:orientation="vertical"
tools:context=".MainActivity">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="請輸入文本" />
</LinearLayout>
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_text_layout);
editText = findViewById(R.id.editText);
// 設置文本監聽器
editText.addTextChangedListener(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) {
// 在文本更改之后執行的操作
}
});
}
}
對于Kotlin,您可以使用以下代碼:
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private lateinit var editText: EditText
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.edit_text_layout)
editText = findViewById(R.id.editText)
// 設置文本監聽器
editText.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
// 在文本更改之前執行的操作
}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
// 在文本更改時執行的操作
}
override fun afterTextChanged(s: Editable) {
// 在文本更改之后執行的操作
}
})
}
}
現在,您已經成功地為OpenHarmony中的EditText組件設置了文本編輯功能。您可以根據需要自定義TextWatcher中的方法來實現特定的文本編輯操作。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。