Android—-點擊事件的四種寫法

Android—-點擊事件的四種寫法。

所有的圖形化操作的應用程序

全部都是死循環

循環的檢測消息的到來

後臺一直監視著系統的各種消息

基於事件的回調

四種寫法

佈局文件中設置onclick屬性

自定義listener

public class MainActivity extends Activity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

Button button1 = (Button) findViewById(R.id.button1);

MyOnclickListener listener = new MyOnclickListener();

button1.setOnClickListener(listener);

}

class MyOnclickListener implements OnClickListener {

@Override

public void onClick(View v) {

Toast.makeText(MainActivity.this, "hhaa", Toast.LENGTH_LONG).show();

}

}

}

匿名內部類

public class MainActivity extends Activity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

Button button1=(Button) findViewById(R.id.button1);

button1.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

Toast.makeText(MainActivity.this, "匿名內部類", Toast.LENGTH_LONG).show();

}

});

}

MainActivity繼承listener

public class MainActivity extends Activity implements OnClickListener {

private Button button1;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

button1 = (Button) findViewById(R.id.button1);

Button button2 = (Button) findViewById(R.id.button2);

Button button3 = (Button) findViewById(R.id.button3);

Button button4 = (Button) findViewById(R.id.button4);

Button button5 = (Button) findViewById(R.id.button5);

button1.setOnClickListener(this);

button2.setOnClickListener(this);

button3.setOnClickListener(this);

button4.setOnClickListener(this);

button5.setOnClickListener(this);

}

@Override

public void onClick(View v) {

int id = v.getId();

switch (id) {

case R.id.button1:

Toast.makeText(this, "第1個按鈕被點擊瞭", Toast.LENGTH_SHORT).show();

break;

case R.id.button2:

Toast.makeText(this, "第2個按鈕被點擊瞭", Toast.LENGTH_SHORT).show();

break;

case R.id.button3:

Toast.makeText(this, "第3個按鈕被點擊瞭", Toast.LENGTH_SHORT).show();

break;

case R.id.button4:

Toast.makeText(this, "第4個按鈕被點擊瞭", Toast.LENGTH_SHORT).show();

break;

case R.id.button5:

Toast.makeText(this, "第5個按鈕被點擊瞭", Toast.LENGTH_SHORT).show();

break;

}

}

}

You May Also Like