Android 如何从2个编辑文本中获取值,并将其求和,然后在没有任何按钮的情况下将其显示为第三个编辑文本

Android 如何从2个编辑文本中获取值,并将其求和,然后在没有任何按钮的情况下将其显示为第三个编辑文本,android,Android,如何从两个EditText中获取值,求和,并将其显示为第三个EditText,而无需单击按钮 这是到目前为止我的代码 public class MainActivity extends Activity { int a,b,c; EditText fst= (EditText)findViewById(R.id.fstdgt); EditText scnd= (EditText)findViewById(R.id.scnddgt); EditText thrd=

如何从两个
EditText
中获取值,求和,并将其显示为第三个
EditText
,而无需单击按钮

这是到目前为止我的代码

public class MainActivity extends Activity {

    int a,b,c;
    EditText fst= (EditText)findViewById(R.id.fstdgt);
    EditText scnd= (EditText)findViewById(R.id.scnddgt);
    EditText thrd= (EditText)findViewById(R.id.thrddgt);
    View v;

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


        a=Integer.parseInt(fst.getText().toString());
        b=Integer.parseInt(scnd.getText().toString());
        c=a+b;
        thrd.setText("" + c);
    }
}

这是行不通的。应用程序每次启动都会崩溃。有人有什么建议吗?

在两个输入编辑框中添加一个textchange侦听器将解决您的问题。我认为应该这样做来解决您的问题:


因为您没有为a、b分配任何值,并且要在不单击“使用文本更改listenerMk”的情况下获取文本,请单击“使用文本更改listenerMk”。你必须添加更多的细节。当应用程序崩溃时,Logcat怎么说?您的文本框最初是否包含任何文本?你到底想要什么样的行为?第三个文本框是否应该仅在应用程序启动时更新?或者它应该在其他两个文本框更新时更改吗?在logcat中,它说空指针例外Mohit可以只为两行编写plz代码以给我提示。它应该在我更改fst和第二个编辑文本中的值时更改
int a, b,c;
String input_a = fst.getText().toString();
String input_b = scnd.getText().toString();

fst.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) {
                if (!input_a.isEmpty() && !intput_b.isEmpty()){
                    a = Integer.parseInt(input_a);
                    b= Integer.parseInt(input_b);
                    c = a+b;
                    String answer_value= "" + c;
                    thrd.setText(answer_value);
                } else thrd.setText("");

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
//and you need to add TextChangeListener for your "scnd" editText as well.
scnd.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) {
                if (!input_a.isEmpty() && !input_b.isEmpty()){
                    a = Integer.parseInt(input_a);
                    b= Integer.parseInt(input_b);
                    c = a+b;
                    String answer_value= "" + c;
                    thrd.setText(answer_value);
                } else thrd.setText("");

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });