前言:
效果如下EditText和TextView的連動,可以運用在很多地方!
分享給你們。
實作 :
1、先在xml做出TextView和EditText2、在MainActivity.java內指定上述兩個東西的元件(findViewById)
3、EditText此次的重點程式碼:
 mEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                 //do something
            }
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                //do something               
             mText.setText(charSequence);
             }
            @Override
            public void afterTextChanged(Editable editable) {
               //do something
            }
        });
/**TextWatcher
*
*beforeTextChanged 在edit改變之前要做的事情
*onTextChanged 在edit改變中要做的事情
*afterTextChanged 在edit改變後要做的事情
*/
我們要改動的就是改變中的這個變數!完整程式碼:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="5dp"
    tools:context="com.chat.a015865.playedit.MainActivity">
    <TextView
        android:id="@+id/show_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:gravity="center"
        android:padding="20dp"
        android:text="Content" />
    <EditText
        android:id="@+id/show_edit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/show_text"
        android:layout_centerInParent="true"
        android:hint="TypeSomething" />
</RelativeLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
    private EditText mEdit;
    private TextView mText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mEdit = (EditText) findViewById(R.id.show_edit);
        mText = (TextView) findViewById(R.id.show_text);
        mEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                mText.setText(charSequence);
            }
            @Override
            public void afterTextChanged(Editable editable) {
            }
        });
    }
}
Demo:
影片中的TextView邊框在這:http://nikeru8.blogspot.tw/2017/03/textview.html
 
 
 
沒有留言:
張貼留言