本帖最後由 tonyh 於 2019-3-23 15:01 編輯
使用 OnClickListener 介面實作一傾聽者物件,藉由覆寫 onClick() 方法定義點擊後所要執行的動作,並以 setOnClickListener() 方法為元件加上傾聽者,完成如下之練習:
MainActivity.java- package com.example.student.myapplication;
- import android.support.v7.app.AppCompatActivity;
- import android.os.Bundle;
- import android.view.View;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.TextView;
- public class MainActivity extends AppCompatActivity {
- EditText editText;
- TextView textView;
- Button button1, button2;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- editText = (EditText) findViewById(R.id.editText);
- textView = (TextView) findViewById(R.id.textView3);
- button1 = (Button) findViewById(R.id.button1);
- button2 = (Button) findViewById(R.id.button2);
- button1.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- editText.setText("");
- textView.setText("");
- }
- });
- button2.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- double a = Double.parseDouble(editText.getText().toString());
- double res = a * 3.3058;
- //String res=String.format("%.4f",a*3.3058);
- textView.setText("面積為: " + res + "平方公尺");
- }
- });
- }
- }
複製代碼 |