编辑文本整数

时间:2014-11-02 21:24:02

标签: android eclipse integer

Android应用程序无法运行,应用程序已停止不幸。错误的代码在哪里?

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

    final EditText edittext1 = (EditText) findViewById(R.id.editText1);
    final Button button1 = (Button) findViewById(R.id.Button01);
    final TextView tw = (TextView) findViewById(R.id.textView1);
    final int valueint = Integer.parseInt(edittext1.getText().toString());

    button1.setOnClickListener(new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {

           tw.setText(Integer.toString(20*valueint));
        }
    });


}

代码是真的吗?

int valueint = Integer.parseInt(edittext1.getText().toString());

1 个答案:

答案 0 :(得分:1)

您正在尝试在create上使用空int值。它可以在EditText中使用一些数字,但是当它为空时它必须崩溃。 tw.setText metod也错了。尝试此代码,工作:

import android.app.Activity;
import android.os.Bundle;
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.TextView;

public class MainActivity1 extends Activity {

    EditText edit;// = (EditText) findViewById(R.id.editText1);
    Button button;// = (Button) findViewById(R.id.button1);
    TextView tw;// = (TextView) findViewById(R.id.textView1);
    int valueint;// = Integer.parseInt(edit.getText().toString());

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

        edit = (EditText) findViewById(R.id.editText1);
        button = (Button) findViewById(R.id.button1);
        tw = (TextView) findViewById(R.id.textView1);

        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {

                valueint = Integer.parseInt(edit.getText().toString());
                tw.setText(String.valueOf(20 * valueint));
            }
        });

    }