如何用EditText中的值改变TextView



我是全新的应用程序制作,我想做的东西,其中有两个edittext(只有数字),然后划分,变成一个百分比,并显示在一个TextView。不幸的是,我不知道我所做的是正确的。这是我的代码

    import android.app.Activity;
    import android.os.Bundle;
    import android.view.Menu;
    import android.widget.EditText;
    import android.widget.TextView;
    public class FirstInformation extends Activity {
EditText eT4 = (EditText)findViewById(R.id.editText4);
EditText eT5 = (EditText)findViewById(R.id.editText5);
TextView tV6 = (TextView)findViewById(R.id.textView6);
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_first_information);
    if (eT4 != null && eT5 != null){
        double numerator = (double) Integer.parseInt(eT4.getText().toString());
        double denominator = (double) Integer.parseInt(eT5.getText().toString());
        double textView = Math.round(numerator/denominator)*100;
        tV6.setText(textView+"");
    }
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.first_information, menu);
    return true;    
}

public void updateTextView() {
    if (eT4 != null && eT5 != null){
        double numerator = (double) Integer.parseInt(eT4.getText().toString());
        double denominator = (double) Integer.parseInt(eT5.getText().toString());
        double textView = Math.round(numerator/denominator)*100;
        tV6.setText(textView+"");
    }
    return;
}

}

任何反馈都会很好。非常感谢!

findViewById() in onCreate()

除零

您的问题是以下代码:

EditText eT4 = (EditText)findViewById(R.id.editText4);
EditText eT5 = (EditText)findViewById(R.id.editText5);
TextView tV6 = (TextView)findViewById(R.id.textView6);

findViewById方法为所有这些调用返回null,因为你在setContentView方法完成之前正在做与UI相关的任务。因此,您可以在那里声明变量,然后在setContentView方法之后初始化它们。

正如其他人所说,findViewById()调用进入onCreate()方法,否则它们将返回null。

还有一件事:updateTextView()永远不会被调用。你可以使用texttwatcher或者onClickListener:

tv6.setOnClickListener(new onClickListener() {
    @Override
    public void onClick(View v) {
        updateTextView();
    }
});

每次点击resulttextview时结果都会更新。顺便说一下,使用texttwatcher(带有afterTextChanged()方法)是一个更好的实践。我建议你看一下指南,然后试试;)

最新更新