本文主要是介绍在Android中如何采用代码的方式打开系统默认的桌面,注意不一定是系统自带的Launcher桌面。在平常开发中我们常常需要快速返回系统默认的桌面,来达到快速显示主页的功能。如果每次都用返回键一级级的返回会比较浪费时间,因此我们可以通过系统的接口来实现打开系统默认的桌面的功能。
一、以下分步讲解如何实现:1、布局中创建打开系统默认桌面的按钮组件
此组件的功能是用于点击后快速进入系统默认桌面,用户可以放置到需要使用该功能的任意界面布局中即可。
android:id="@+id/open_home"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="打开系统默认桌面" />
2、代码中实例化该按钮组件,并绑定当前点击事件的监听器
此功能主要是获取用户点击事件,监听到点击事件后,并调用打开系统默认桌面的接口。
// 初始化组件
Button openHome = (Button) findViewById(R.id.open_home);
// 绑定监听器
openHome.setOnClickListener(this);
二、实际代码应用:1、布局文件 - test_open_home.xml
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
android:id="@+id/open_home"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="打开系统默认桌面" />
2、代码文件 - TestOpenHome.java
package com.test;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
/**
* 测试系统默认桌面的跳转功能
*
* @version V5
*/
public class TestOpenHome extends Activity implements OnClickListener {
/** 打开系统默认桌面按钮 */
private Button open_home = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_open_home);
// 初始化组件
open_home = (Button) findViewById(R.id.open_home);
// 绑定监听器
open_home.setOnClickListener(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.open_home:
// 跳转到系统默认桌面
openHome();
break;
default:
break;
}
}
/**
* 打开系统默认桌面
*/
public void openHome() {
Intent homeIntent = new Intent(Intent.ACTION_MAIN);
homeIntent.addCategory(Intent.CATEGORY_HOME);
startActivity(homeIntent);
}
}