四種點擊事件
(1)采用內部類的方式去實現OnClickListener
(2)匿名內部類
(3)當前類imp OnClickListener
(4)onclick
1、設置按鈕的單擊事件的監聽器,創建匿名內部類
bt_call.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//撥打電話號碼
String phone = et_phone.getText().toString().trim();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_CALL);
System.out.println("phone="+phone);
intent.setData(Uri.parse("tel://"+phone));
startActivity(intent);
}
});
2、創建一個內部類
private class MyOnClickListener implements OnClickListener{
@Override
public void onClick(View v) {
//撥打電話號碼
String phone = et_phone.getText().toString().trim();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_CALL);
System.out.println("phone="+phone);
intent.setData(Uri.parse("tel://"+phone));
startActivity(intent);
}
}
//別忘記給按鈕添加一個單擊事件的監聽器
bt_call.setOnClickListener(new MyOnClickListener());
3、在布局文件中給按鈕添加一個單擊事件的響應方法,然后在代碼中實現這個方法
(1)在布局文件中給按鈕添加一個單擊事件的響應方法
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="撥打"
android:id="@+id/bt_call"
android:onClick="call"
/>
(2)在代碼中實現這個方法
//view 表示的是按鈕這個視圖
public void call(View view){
//撥打電話號碼
String phone = et_phone.getText().toString().trim();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_CALL);
System.out.println("phone="+phone);
intent.setData(Uri.parse("tel://"+phone));
startActivity(intent);
}
.四種方法寫按鈕點擊事件
1.匿名內部類的方式
2. 創建一個類實現onclickListener,實現onclick方法,設置控件點擊事件時傳一個類的對象。
3. 讓當前類實現onclickListener,設置控件點擊事件時傳一個this。這種方式適合按鈕比較多的情況,一般在公司采用該方式。
4. 在布局文件中為控件添加一個onclick屬性,在布局對應的Activity中寫一個一onclick屬性值為名的方法,要public,傳一個View類型的參數。比較適合做簡單的測試。
