1 package com.geli_2.sujie.sujiegeili2testbutton; 2 3 import android.os.Bundle; 4 import android.support.v7.app.AppCompatActivity; 5 import android.vi... ...
1 package com.geli_2.sujie.sujiegeili2testbutton; 2 3 import android.os.Bundle; 4 import android.support.v7.app.AppCompatActivity; 5 import android.view.View; 6 import android.widget.Button; 7 import android.widget.Toast; 8 9 public class MainActivity extends AppCompatActivity implements View.OnClickListener 10 { 11 12 private Button mBtClick; 13 private Button mBtClick2; 14 private Button mBtClick3; 15 private Button mBtClick4; 16 17 @Override 18 protected void onCreate(Bundle savedInstanceState) 19 { 20 super.onCreate(savedInstanceState); 21 setContentView(R.layout.activity_main); 22 mBtClick = (Button) findViewById(R.id.btnTest1); //1、fdv 找到button id 23 // 2、 Alt Ctrl F 形成類全局Field 24 mBtClick.setOnClickListener(new View.OnClickListener() //3、鍵入此行代碼自動嵌入內部類方法 25 { 26 @Override 27 public void onClick(View v) 28 { //4、 Toast tab tab 調出toast 方法 以上為方法一 29 Toast.makeText(MainActivity.this, "hello world1", Toast.LENGTH_SHORT).show(); 30 } 31 }); 32 33 34 mBtClick2 = (Button) findViewById(R.id.btnSample2); //5、找出button 2 的 button id fdv 35 mBtClick2.setOnClickListener(new Button_2_OnClickListener()); //9、實例化方法給button 綁定 以上是方法二 36 mBtClick3 = (Button) findViewById(R.id.btnTry3); //10、找出button 3 的 button id fdv 37 mBtClick3.setOnClickListener(this); //11、 this 表示 main acitivity 38 //12 但是這裡是方法參數是onclicklistener介面,此處 this Alt Enter 會在此方法上加上實現的介面以上是方法三 39 mBtClick4 = (Button) findViewById(R.id.btnExample4); //5、找出button 4 的 button id fdv 方法四這行沒用 40 41 42 } 43 44 /** 45 * Called when a view has been clicked. 46 * 47 * @param v The view that was clicked. 48 */ 49 @Override 50 public void onClick(View v) 51 { 52 Toast.makeText(MainActivity.this, "hello world 3", Toast.LENGTH_SHORT).show();//方法三 53 } 54 55 class Button_2_OnClickListener implements View.OnClickListener //6、設置一個 click 方法 命名後繼承自 view 56 // onclicklistener 57 //7、 後在 繼承 implements 上 alt + enter 來實現方法 58 { 59 60 /** 61 * Called when a view has been clicked. 62 * 63 * @param v The view that was clicked. 64 */ 65 @Override 66 public void onClick(View v) 67 { 68 Toast.makeText(MainActivity.this, "hello world 2", Toast.LENGTH_SHORT).show();//方法二 69 } 70 } 71 public void click(View view) 72 { 73 Toast.makeText(MainActivity.this, "hello world 4", Toast.LENGTH_SHORT).show();//方法四 74 } 75 76 }