单个edittext必须调用textwatcher或充当textview android

时间:2014-10-15 20:33:08

标签: android textwatcher

您好我的应用程序中有2个editText,如果edittext输入来自某个方法,则必须显示值,如果editText的输入来自键盘,则必须调用textwatcher。

即:

  • 如果edittext1从虚拟键盘输入,则触发TextWatcher,它将调用方法并在edittext2中显示值[此处edittext2充当textview]

  • 如果edittext2从虚拟键盘输入,则触发textwatcher,它将调用方法并在edittext1中显示结果[此处edittext1充当textview]

这可能吗?如果是这样,请告诉我要遵循的概念。

感谢

1 个答案:

答案 0 :(得分:0)

直接实施可能 CRASH 您的应用。您可以使用标志变量

来解决问题
public class MainActivity extends Activity {

    EditText et1, et2;
    String flag = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        et1 = (EditText) findViewById(R.id.editText1);
        et2 = (EditText) findViewById(R.id.editText2);

        // Here update the flag variable to keep track which text view is in use
        et1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                flag = "ET1";
            }
        });

        // Here update the flag variable to keep track which text view is in use
        et2.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                flag = "ET2";
            }
        });

        et1.addTextChangedListener(new TextWatcher() {

            public void afterTextChanged(Editable s) {
            }

            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
            }

            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {
                // Set the value of editText2 value here if only flag contains
                // ET1
                // This will prevent changes if ET2 is being used
                if (flag.equals("ET1")) {
                    et2.setText(s);
                }
            }
        });

        et2.addTextChangedListener(new TextWatcher() {

            public void afterTextChanged(Editable s) {
            }

            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
            }

            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {
                // Set the value of editText1 value here only if flag equals ET2
                if (flag.equals("ET2")) {
                    et1.setText(s);
                }
            }
        });
    }
}

运行在您输入之前,双击EditText。您可以通过在适当的情况下启用和禁用edittext来进一步改进这一点,因此您只需单击即可实现相同的目标。

如果您对代码有疑问,请在下方发表评论。