我正在练习,我被困在一个点上,我想将用户输入文本从 EditText 设置为 TextView 但我不知道该怎么做,所以我在这里搜索它,我发现了这个How to get EditText value to TextView 在 android [关闭] 中键入时没有按钮单击 我遵循此但它不起作用所以我决定发布一个新问题以了解是否有任何改进。
这是我的简单 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"
android:background="#fff"
android:orientation="vertical"
android:padding="10dp"
tools:context=".MainActivity">
<TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="40dp"
android:text="Hello World!"
android:textColor="#000"
android:textSize="20sp" />
<TextView
android:id="@+id/tv2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:text="Hello World!"
android:textColor="#000"
android:textSize="20sp" />
<EditText
android:id="@+id/et1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:inputType="text" />
<EditText
android:id="@+id/et2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:inputType="text" />
</LinearLayout>
这是我的java代码
package com.example.ontimedata;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView tv1, tv2;
EditText et1, et2;
String data1, data2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = findViewById(R.id.tv1);
tv2 = findViewById(R.id.tv2);
et1 = findViewById(R.id.et1);
et2 = findViewById(R.id.et2);
TextWatcher textWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
Log.d("TAG", "beforeTextChanged: ");
data1 = et1.getText().toString();
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Log.d("TAG", "onTextChanged: ");
data1 = et1.getText().toString();
}
@Override
public void afterTextChanged(Editable s) {
Log.d("TAG", "afterTextChanged: ");
data1 = et1.getText().toString();
}
};
tv1.addTextChangedListener(textWatcher);
Log.d("TAG", "onCreate: ");
TextWatcher textWatcher1 = 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) {
data2 = et2.getText().toString();
}
@Override
public void afterTextChanged(Editable s) {
}
};
tv2.addTextChangedListener(textWatcher1);
}
}
如果您回答了这个问题,请提前感谢。