0

ユーザーが値を入力してから下のボタンを押すAndroidアプリケーションを作成しようとしています。ボタンを押すと、編集テキスト値をそれ自体に追加し、結果を画面に表示します。たとえば、ユーザーが編集テキストに 2 と入力した場合、ユーザーがボタンを押すと、アプリに 2+2 を実行させ、結果 4 を画面に表示します。これが私がこれまでに持っているものです...

int AnsNum;
EditText Km;
Button KmPL;
TextView Ans;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Km = (EditText) findViewById(R.id.etKm);
    KmPL = (Button) findViewById(R.id.button1);
    Ans = (TextView) findViewById(R.id.tvAns);

    KmPL.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            Km = (EditText) findViewById(R.id.etKm);
            int etKm = new Integer(Km.getText().toString()).intValue();

            int AnsNum = etKm+etKm;
            Ans.setText(AnsNum);        
        }
    });
}

メインのJavaファイルと...

<TextView
    android:id="@+id/tvAns"
    android:textSize="100dp"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:text="0" />

<EditText
    android:id="@+id/etKm"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="Km"
    android:textSize="100dp"
    android:inputType="numberSigned" />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="75dp"
    android:text="Km per Litres" />

main.xml ファイル内。ただし、携帯電話またはエミュレーターでアプリの天気予報を実行しようとすると、予期せず停止したと表示され、もう一度やり直してください。何度か試しましたが、うまくいきません。

これはおそらくばかげた質問だと思いますが、私はプログラミングにまったく慣れていないので、間違っていることを教えていただければ、負荷がかかります。

4

2 に答える 2

0

あなたが書くとき、あなたの主な問題はここにあると思います:

Ans.setText(AnsNum);

TextView.setText(int resId)を呼び出そうとしていますが、これは間違いなくあなたが望むものではありません。代わりに、Ivan Seidel が言ったように、電話する必要があります。

Ans.setText("" + AnsNum);

文字列連結演算子を使用して AnsNum を String に変換します(また、これは連結演算子ではなく StringBuilder クラスを使用するようにコンパイラーによって最適化されます。これはより効率的であるためです)。


また、これの代わりに:

int etKm = new Integer(Km.getText().toString()).intValue();

次のように、クラス Integer public static Integer valueOf(String s) の静的メソッドを呼び出す方がよいでしょう。

int etKm = Integer.valueOf(Km.getText().toString());

自動的にint型にキャストされるInteger objectを返します

于 2012-08-05T00:19:36.780 に答える