Java 是否可以在不单击任何按钮的情况下在应用程序中自动填充编辑文本?

Java 是否可以在不单击任何按钮的情况下在应用程序中自动填充编辑文本?,java,android,database,sqlite,autofill,Java,Android,Database,Sqlite,Autofill,我有这个表单供用户填写,其中一个编辑文本是BMI,我在想,在用户输入身高和体重后,是否可以自动填写BMI编辑文本,而无需单击任何按钮。我在谷歌上搜索到了一个叫做文本观察者的东西。我尝试在代码中实现它,但是当我运行应用程序时,BMI的编辑文本仍然是空的,数据库也是空的 package mdad.project; import com.example.manandhowproject.R; import android.app.Activity; import android.content.I

我有这个表单供用户填写,其中一个编辑文本是BMI,我在想,在用户输入身高和体重后,是否可以自动填写BMI编辑文本,而无需单击任何按钮。我在谷歌上搜索到了一个叫做文本观察者的东西。我尝试在代码中实现它,但是当我运行应用程序时,BMI的编辑文本仍然是空的,数据库也是空的

package mdad.project;

import com.example.manandhowproject.R;

import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Userreg extends Activity implements TextWatcher {
    SQLiteDatabase db;
    Button btnNext;
    EditText etName, etAge, etHeight, etWeight, etBMI;
    double result;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.userreg);
        etName = (EditText) findViewById(R.id.etName);
        etAge = (EditText) findViewById(R.id.etAge);
        etHeight = (EditText) findViewById(R.id.etHeight);
        etWeight = (EditText) findViewById(R.id.etWeight);
        etBMI = (EditText) findViewById(R.id.etBMI);
        Button button = (Button) findViewById(R.id.btnSignOut);
        button.setOnClickListener(new OnClickListener() {
            public void onClick(View V) {
                Toast.makeText(getApplicationContext(), "Log Out Success ! ", Toast.LENGTH_LONG).show();
                Intent msg2 = new Intent(Userreg.this, Login.class);
                startActivity(msg2);
            }
        });

        Button btnNext = (Button) findViewById(R.id.btnNext);
        btnNext.setOnClickListener(new OnClickListener() {
            public void onClick(View V) {
                String name = etName.getText().toString();
                String age = etAge.getText().toString();
                int nAge = new Integer(age).intValue();
                String height = etHeight.getText().toString();
                int nHeight = new Integer(height).intValue();
                String weight = etWeight.getText().toString();
                int nWeight = new Integer(weight).intValue();
                String bmi = etBMI.getText().toString();
                String sql = "insert into UserInfo (Name,Age,Height,Weight,BMI) values( '" + name + "','" + nAge + "','" + nHeight + "', '" + nWeight + "', '" + bmi + "')";
                String result = updateTable(sql);

                Intent msg3 = new Intent(Userreg.this, Regsuccess.class);
                startActivity(msg3);
            }
        });
        String sql = "create table if not exists UserInfo (recld integer PRIMARY KEY autoincrement, Name text, Age text, Height text, Weight text, BMI text )";
        String result = createDatabase(sql, "UserInf.db");
    }

    private void calculate() {

        String height = etHeight.getText().toString();
        int nHeight = new Integer(height).intValue();
        String weight = etWeight.getText().toString();
        int nWeight = new Integer(weight).intValue();
        result = nWeight / (nHeight * nHeight);
        String textResult = "" + result;
        etBMI.setText(textResult);

    }


    String createDatabase(String sql, String dbName) {
        try {
            System.out.println(sql);
            db = SQLiteDatabase.openOrCreateDatabase("sdcard/" + dbName, null);
            db.beginTransaction();
            db.execSQL(sql);
            db.setTransactionSuccessful();
            db.endTransaction();
        } catch (Exception e) {
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
            System.out.println(e.toString());
            return ("error open DB");
        }

        return "";
    }

    String updateTable(String sql) {
        try {
            System.out.println(sql);
            db.beginTransaction();
            db.execSQL(sql);
            db.setTransactionSuccessful();
            db.endTransaction();

        } catch (Exception e) {
            System.out.println(e.toString());
            return ("Error updating DB");
        }
        return ("DB updated");
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.second, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
        int after) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        // TODO Auto-generated method stub

    }

    @Override
    public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub
        calculate();
    }
}
你失踪了

etHeight.addTextChangedListener(this);
etWeight.addTextChangedListener(this);
onCreate()

另外,更新您的
calculate()
方法,因为它包含BMI计算的错误:

private void calculate() {

    try {
        String height = etHeight.getText().toString();
        int nHeight = Integer.parseInt(height);
        String weight = etWeight.getText().toString();
        int nWeight = Integer.parseInt(weight);
        result = nWeight / (nHeight * nHeight);
        String textResult = "" + result;
        etBMI.setText(textResult);
    }
    catch (NumberFormatException e) {
        etBMI.setText("");
    }
}

你可以用两种方法

首先使用
TextWatcher
,因为每个人都在给出解决方案。以及

第二种方法是,对EditText使用
OnFocusChangeListener
。下面是你如何实现它的示例

EditText one = findViewById(R.id.one);
EditText two = findViewById(R.id.two);
EditText three = findViewById(R.id.three);

three.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean hasFocus) {
            if (hasFocus){
                Double ONE = Double.parseDouble(one.getText().toString().trim());
                Double TWO = Double.parseDouble(two.getText().toString().trim());
                Double THREE = ONE+TWO;
                three.setText(String.valueOf(THREE));
                Log.i("tag", "onFocusChange: "+THREE);
                //or you can perform any other task
            }
        }
});

如上例所示,当用户将焦点设置为第三个编辑文本时,它将从第一个编辑文本和第二个编辑文本中获取值并显示结果

这是结果……问题不是关于如何使用
TextWatcher
,而是更具体的问题,因为它还包含其他错误,导致用户的代码无法按预期工作。嘿,我已经按照你的建议添加了两行语句,但现在每当我尝试输入身高或体重的任何数字时,整个应用程序都会崩溃。但当我输入字母表时,它不会崩溃。(我认为这是因为我将edittext输入值设置为仅数字)因此您可以进一步建议吗?这是因为您没有验证
calculate()
方法中的输入。当文本无效时,将引发异常(导致崩溃)。我已经更新了我的答案,请查看。它可能需要一些调整,因为我还没有运行代码。最后,如果答案对你有帮助,请接受:)嗨,非常感谢你的建议。目前,我可以让自动填充工作,但它保持自动填充的值是0,无论发生什么。你能进一步建议吗?我真的很感谢你的帮助好的,还有一个错误<代码>结果是
双精度
,但是表达式
nWeight/(nHeight*nHeight)
(在
calculate()
中)会产生一个
int
,从而导致结果为0。将其更改为
(双倍)nWeight/(nHeight*nHeight)
。好的,我设法让它工作了,非常感谢!