Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 實用代碼片段大集合

編輯:關於 Android 程式設計

在日常 Android 開發中,許多常見功能都有固定的實現套路。本文整理了若干高頻使用的實用代碼片段,方便隨時查閱。

一、獲取應用版本號

PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0);

int versionCode = info.versionCode;

String versionName = info.versionName;

二、獲取安裝包資訊

透過 PackageManager 解析指定的 apk 檔案,可取得應用名稱、包名、版本及圖示:

PackageManager pm = getPackageManager();

PackageInfo info = pm.getPackageArchiveInfo(archiveFilePath, PackageManager.GET_ACTIVITIES);

if (info != null) {

ApplicationInfo appInfo = info.applicationInfo;

String appName = pm.getApplicationLabel(appInfo).toString();

String packageName = appInfo.packageName;

Drawable icon = pm.getApplicationIcon(appInfo);

}

三、獲取路徑與已安裝列表

取得當前程式路徑:

getApplicationContext().getFilesDir().getAbsolutePath()

取得已安裝的程式列表:

List<PackageInfo> packageInfoList = getPackageManager().getInstalledPackages(0);

四、獲取圖片、應用名與包名

遍歷應用列表並取得圖示等資訊,常用於分享選單:

PackageManager pManager = getPackageManager();

List<PackageInfo> appList = Utils.getAllApps(this);

for (int i = 0; i < appList.size(); i++) {

PackageInfo pinfo = appList.get(i);

Drawable icon = pManager.getApplicationIcon(pinfo.applicationInfo);

}

五、解決 ListView 中 Item 無法點擊的問題

當 item 內含有按鈕等控件時,item 本身可能無法觸發點擊。解決方式:

1. 在 item 布局上加入 android:descendantFocusability="blocksDescendants"

2. 在 ListView 中加入 android:focusable="true"

六、限制文本框只能輸入英文與數字

透過 android:digits 屬性指定允許輸入的字元,即可避免中文輸入。

七、獲取螢幕寬高

DisplayMetrics displayMetrics = new DisplayMetrics();

getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

int height = displayMetrics.heightPixels;

int width = displayMetrics.widthPixels;

八、獲取設備型號與系統版本

String device_model = Build.MODEL;

String version_sdk = Build.VERSION.SDK;

String version_release = Build.VERSION.RELEASE;

九、獲取應用下所有 Activity

public static ArrayList<String> getActivities(Context ctx) {

ArrayList<String> result = new ArrayList<String>();

Intent intent = new Intent(Intent.ACTION_MAIN, null);

intent.setPackage(ctx.getPackageName());

for (ResolveInfo info : ctx.getPackageManager().queryIntentActivities(intent, 0)) {

result.add(info.activityInfo.name);

}

return result;

}

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved