记录一下Android开发过程中用到的各种有用的代码、工具、技巧,以备需要时使用。
双击返回按钮退出程序
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
* 双击返回按钮退出程序
*
@param keyCode keyCode
*
@param event event
*
@return 双击返回true,否则返回super.onKeyDown(keyCode,event)
*/
protected boolean doubleClickToQuit(int keyCode, KeyEvent event){
if(event.getAction()== KeyEvent.ACTION_DOWN&&KeyEvent.KEYCODE_BACK==keyCode){
long currentTime = System.currentTimeMillis();
if((currentTime-touchTime)>=
2000){
Toast.makeText(
this,getResources().getString(R.string.press_again_to_quit), Toast.LENGTH_SHORT).show();
touchTime=currentTime;
}
else{
finish();
}
return
true;
}
return
super.onKeyDown(keyCode,event);
}
|
显示/隐藏 ActionBar
1
2
3
4
5
6
7
8
9
|
* 显示/隐藏 ActionBar
*
@param flag true=显示,false=隐藏
*/
protected void showActionBar(boolean flag){
if(getSupportActionBar()!=
null){
getSupportActionBar().setDisplayShowTitleEnabled(flag);
}
}
|
设置StatusBar是否为透明
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
* 设置StatusBar是否为透明
*
@param makeTranslucent true=透明,false=不透明
*/
@TargetApi(Build.VERSION_CODES.KITKAT)
protected void setStatusBarTranslucent(boolean makeTranslucent) {
if (makeTranslucent) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
if(getSupportActionBar()!=
null) {
getSupportActionBar().setDisplayShowTitleEnabled(
false);
}
}
else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
}
|
是否显示返回按钮
1
2
3
4
5
6
7
8
9
|
* 是否显示返回按钮
*
@param flag true=显示,false=隐藏
*/
protected void ShowBackToParentButton(boolean flag){
if (getSupportActionBar() !=
null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(flag);
}
}
|
强制ActionBar显示Overflow菜单
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
* 强制ActionBar显示Overflow菜单
*/
protected void getOverflowMenu() {
try {
ViewConfiguration config = ViewConfiguration.get(
this);
Field menuKeyField = ViewConfiguration.class.getDeclaredField(
"sHasPermanentMenuKey");
if(menuKeyField !=
null) {
menuKeyField.setAccessible(
true);
menuKeyField.setBoolean(config,
false);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
|
定义activity返回动画
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
* ActionBar 按钮点击事件,此处处理了左上角返回按钮的动画效果
*
@param item 按钮
*
@return super.onOptionsItemSelected(item)
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(
this);
overridePendingTransition(R.anim.slide_left_in,R.anim.slide_right_out);
return
true;
}
return
super.onOptionsItemSelected(item);
}
|
R.anim.slide_left_in.xml:
1
2
3
4
5
6
7
8
9
|
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<translate
android:duration=
"200"
android:fromXDelta=
"-100.0%p"
android:toXDelta=
"0.0" />
</set>
|
R.anim.slide_right_out.xml:
1
2
3
4
5
6
7
8
9
|
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<translate
android:duration=
"200"
android:fromXDelta=
"0.0"
android:toXDelta=
"100.0%p" />
</set>
|