MainActivity:
package
com.testnbackpressed;
import
android.os.Bundle;
import
android.view.KeyEvent;
import
android.app.Activity;
/**
* Demo描述:
* 处理Back键按下事件
*
* 注意事项:
* 以下两种方法勿一起使用
*/
public
class
MainActivity
extends
Activity {
@Override
protected
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
/**
* 监听Back键按下事件,方法1:
* 注意:
* super.onBackPressed()会自动调用finish()方法,关闭
* 当前Activity.
* 若要屏蔽Back键盘,注释该行代码即可
*/
@Override
public
void
onBackPressed() {
super
.onBackPressed();
System.out.println(
"按下了back键 onBackPressed()"
);
}
/**
* 监听Back键按下事件,方法2:
* 注意:
* 返回值表示:是否能完全处理该事件
* 在此处返回false,所以会继续传播该事件.
* 在具体项目中此处的返回值视情况而定.
*/
@Override
public
boolean
onKeyDown(
int
keyCode, KeyEvent event) {
if
((keyCode == KeyEvent.KEYCODE_BACK)) {
System.out.println(
"按下了back键 onKeyDown()"
);
return
false
;
}
else
{
return
super
.onKeyDown(keyCode, event);
}
}
@Override
protected
void
onDestroy() {
super
.onDestroy();
System.out.println(
"执行 onDestroy()"
);
}
}
main.xml
<
RelativeLayout
xmlns:android
=
"http://schemas.android.com/apk/res/android"
xmlns:tools
=
"http://schemas.android.com/tools"
android:layout_width
=
"match_parent"
android:layout_height
=
"match_parent"
>
<
TextView
android:layout_width
=
"wrap_content"
android:layout_height
=
"wrap_content"
android:text
=
"对于Back键的两种处理方法"
android:layout_centerInParent
=
"true"
android:textSize
=
"20sp"
/>
</
RelativeLayout
>