个人对settings一些学习总结,在介绍Settings一级菜单栏之前先讲解一下如何添加一级菜单栏,这样可以更好的理解后面的一级菜单栏显示流程
添加一级菜单栏
在Settings.java中添加代码
public static class TestSettingsActivity extends SetttingsActvity{}
添加了activity之后肯定是需要在清单文件中进行配置
<activity
android:name="Settings$TestSettingsActivity"
android:label="标签"
android:icon="图标"
android:taskAffinity="com.android.settings"
android:parentActivityName="Settings">
<!-- android:priority 跟一级菜单栏排序相关,在后面的显示流程会讲解 -->
<intent-filter android:priority="9">
<action android:name="com.android.settings.action.SETTINGS" />
</intent-filter>
<!-- 显示在那个分类,这个定义设置是根据源码配置相关的,后面显示流程会说明 -->
<meta-data android:name="com.android.settings.category"
android:value="com.android.settings.category.device" />
<!-- 点击后调整的fragment页,如果不设置会显示设置主页面,后面会说明为什么-->
<meta-data android:name="com.android.settings.FRAGMENT_CLASS"
android:value="com.android.settings.DisplaySettings" />
<!-- -->
<meta-data android:name="com.android.settings.PRIMARY_PROFILE_CONTROLLED"
android:value="true" />
<!-- 标题,如果不设置标题则会采用label标签的内容 -->
<meta-data android:name="com.android.settings.title"
android:resource="标题"/>
<!-- 提示 -->
<meta-data android:name="com.android.settings.summary"
android:resource="提示内容"/>
</activity>
配置好后就可以在一级菜单栏看见你设置的一级菜单了
Settings一级菜单栏显示流程
其实通过添加时我们可以发现Activity继承的是SettingsActivity,包括Settings.java也是继承的SettingsActivity,可以判断SettingsActivity是非常重要的一个activity
Settings在打开运行的时候会先执行SettingsActivity中onCreate方法,在onCreate中有一个getMetaData方法,看源码
private void getMetaData() {
try {
ActivityInfo ai = getPackageManager().getActivityInfo(getComponentName(),
PackageManager.GET_META_DATA);
if (ai == null || ai.metaData == null) return;
mFragmentClass = ai.metaData.getString(META_DATA_KEY_FRAGMENT_CLASS);
} catch (NameNotFoundException nnfe) {
// No recovery
Log.d(LOG_TAG, "Cannot get Metadata for: " + getComponentName().toString());
}
}
获取你在清单文件里配置的activity中的name为FRAGMENT_CLASS的meta-data参数配置fragment,比如上面我们添加的一级菜单栏,我们设置的点击后跳转的页面是DisplaySettings,那就是获取的就是这个页面
然后会执行Settings重写的getIntent方法,看源码
@Override
public Intent getIntent() {
Intent superIntent = super.getIntent();
String startingFragment = getStartingFragmentClass(superIntent);
...
}
private String getStartingFragmentClass(Intent intent) {
if (mFragmentClass != null) return mFragmentClass;
String intentClass = intent.getComponent().getClassName();
...
return intentClass;
}
再结合整体源码,我们可以看出来,如果获取到跳转的页面就显示,获取不到就显示设置主页面,接着往下走
mIsShowingDashboard = className.equals(Settings.class.getName());
...
setContentView(mIsShowingDashboard ?
R.layout.settings_main_dashboard : R.layout.settings_main_prefs);
获取是否是设置主页面,通过获取的mIsShowingDashboard 参数来判断显示一级菜单栏页面还是二级菜单栏页面
然后会执行 launchSettingFragment 方法
@VisibleForTesting
void launchSettingFragment(String initialFragmentName, boolean isSubSettings, Intent intent) {
if (!mIsShowingDashboard && initialFragmentName != null) {
setTitleFromIntent(intent);
Bundle initialArguments = intent.getBundleExtra(EXTRA_SHOW_FRAGMENT_ARGUMENTS);
switchToFragment(initialFragmentName, initialArguments, true, false,
mInitialTitleResId, mInitialTitle, false);
} else {
// Show search icon as up affordance if we are displaying the main Dashboard
mInitialTitleResId = R.string.dashboard_title;
switchToFragment(DashboardSummary.class.getName(), null /* args */, false, false,
mInitialTitleResId, mInitialTitle, false);
}
}
最后会执行switchToFragment 方法
/**
* Switch to a specific Fragment with taking care of validation, Title and BackStack
*/
private Fragment switchToFragment(String fragmentName, Bundle args, boolean validate,
boolean addToBackStack, int titleResId, CharSequence title, boolean withTransition) {
Log.d(LOG_TAG, "Switching to fragment " + fragmentName);
...
Fragment f = Fragment.instantiate(this, fragmentName, args);
...
return f;
}
根据这两段代码,我们可以看出设置主页面最后展示的是DashboardSummary,然后我们看DashboardSummary中onCreate方法
@Override
public void onCreate(Bundle savedInstanceState) {
long startTime = System.currentTimeMillis();
super.onCreate(savedInstanceState);
final Activity activity = getActivity();
String[] categoriesName = activity.getResources().getStringArray(R.array
.freeme_dashboard_categories);
...
}
categoriesName就是分类列表,根据源码流程,最后会通过updateCategory方法获取列表数据,根据源码继续往下走会走到CategoryManager中的tryInitCategories方法,在这个方法中调用了TileUtils中的getCategories方法,其实走到这里我们会发现,获取一级菜单栏列表及排序并不是在Settings里进行控制,而是在SettingsLib里进行控制
说会TileUtils,这个类说白了就是通过action及packagename来获取在可以显示的action及action的信息,我们看里面的一些方法
getTilesForAction,这个方法就是通过action及packagename来获取可显示的一级菜单栏,看源码,最终会走到这个方法里面
private static void getTilesForAction(Context context,
UserHandle user, String action, Map<Pair<String, String>, Tile> addedCache,
String defaultCategory, ArrayList<Tile> outTiles, boolean requireSettings,
boolean usePriority, String settingPkg) {
Intent intent = new Intent(action);
if (requireSettings) {
intent.setPackage(settingPkg);
}
getTilesForIntent(context, user, intent, addedCache, defaultCategory, outTiles,
usePriority, true, true);
}
方法里执行的getTilesForIntent就是通过action及packagename获取的菜单栏进行整理并放入一整个列表中,之后会执行这段代码
HashMap<String, DashboardCategory> categoryMap = new HashMap<>();
for (Tile tile : tiles) {
DashboardCategory category = categoryMap.get(tile.category);
if (category == null) {
category = createCategory(context, tile.category, categoryDefinedInManifest);
if (category == null) {
Log.w(LOG_TAG, "Couldn't find category " + tile.category);
continue;
}
categoryMap.put(category.key, category);
}
category.addTile(tile);
}
ArrayList<DashboardCategory> categories = new ArrayList<>(categoryMap.values());
for (DashboardCategory category : categories) {
category.sortTiles();
}
Collections.sort(categories, CATEGORY_COMPARATOR);
将所有的一级菜单栏进行分类和排序,排序一般是根据priority惨数来判断,思考一下,如果两个设置的priority参数一致,怎么排序,看源码
//CategoryManager
private synchronized void tryInitCategories(Context context, boolean forceClearCache,
String settingPkg) {
if (mCategories == null) {
if (forceClearCache) {
mTileByComponentCache.clear();
}
mCategoryByKeyMap.clear();
//通过TileUtils中的getCategories方法获取设置列表
mCategories = TileUtils.getCategories(context, mTileByComponentCache,
false /* categoryDefinedInManifest */, mExtraAction, settingPkg);
for (DashboardCategory category : mCategories) {
mCategoryByKeyMap.put(category.key, category);
}
/*/ freeme.wanglei, 20180622. FreemeAppTheme, no need backword compat for freeme style
backwardCompatCleanupForCategory(mTileByComponentCache, mCategoryByKeyMap);
//*/
//排序方法
sortCategories(context, mCategoryByKeyMap);
filterDuplicateTiles(mCategoryByKeyMap);
}
}
@VisibleForTesting
synchronized void sortCategories(Context context,
Map<String, DashboardCategory> categoryByKeyMap) {
for (Entry<String, DashboardCategory> categoryEntry : categoryByKeyMap.entrySet()) {
categoryEntry.getValue().sortTiles(context.getPackageName());
}
}
//DashboardCategory
public synchronized void sortTiles(String skipPackageName) {
// Sort mTiles based on [priority, package within priority]
Collections.sort(mTiles, (tile1, tile2) -> {
final String package1 = tile1.intent.getComponent().getPackageName();
final String package2 = tile2.intent.getComponent().getPackageName();
final int packageCompare = CASE_INSENSITIVE_ORDER.compare(package1, package2);
// First sort by priority
//先通过两个设置的priority 参数来排序,如果priority 值一致
final int priorityCompare = tile2.priority - tile1.priority;
if (priorityCompare != 0) {
return priorityCompare;
}
// Then sort by package name, skip package take precedence
//根据设置名称的首字母的ASCII码来判断
if (packageCompare != 0) {
if (TextUtils.equals(package1, skipPackageName)) {
return -1;
}
if (TextUtils.equals(package2, skipPackageName)) {
return 1;
}
}
return packageCompare;
});
}