工具类的特点:
- 使用参数传递的方法代替成员变量。(通过参数传递,使得方法能够声明为static)
- 方法大多是static方法。
- 通过私有的构造器来强化他的工具类的角色。
- 工具类常命名为:XXXUtils
一个例子:
package com.android.calendar;
//省略无关代码。
public class Utils {
public static int getViewTypeFromIntentAndSharedPref(Activity activity) {//使用的Activity对象,通过参数传递,而不是使用成员变量
// 一些处理
return prefs.getInt(
GeneralPreferences.KEY_START_VIEW, GeneralPreferences.DEFAULT_START_VIEW);
}
public static String getWidgetUpdateAction(Context context) {//使用的Activity对象,通过参数传递,而不是使用成员变量
return context.getPackageName() + ".APPWIDGET_UPDATE";
}
/**
* Gets the intent action for telling the widget to update.
*/
public static String getSearchAuthority(Context context) {
return context.getPackageName() + ".CalendarRecentSuggestionsProvider";
}
static void setSharedPreference(Context context, String key, boolean value) {//干脆把key和value都传递进去了
SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(key, value);
editor.apply();
}
static void setSharedPreference(Context context, String key, int value) {
SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(key, value);
editor.apply();
}
public static MatrixCursor matrixCursorFromCursor(Cursor cursor) {
MatrixCursor newCursor = new MatrixCursor(cursor.getColumnNames());
int numColumns = cursor.getColumnCount();
String data[] = new String[numColumns];
cursor.moveToPosition(-1);
while (cursor.moveToNext()) {
for (int i = 0; i < numColumns; i++) {
data[i] = cursor.getString(i);
}
newCursor.addRow(data);
}
return newCursor;
}
/**
* Sends an intent to launch the top level Calendar view.
*
* @param context
*/
public static void returnToCalendarHome(Context context) {
Intent launchIntent = new Intent(context, AllInOneActivity.class);
launchIntent.setAction(Intent.ACTION_DEFAULT);
launchIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
launchIntent.putExtra(INTENT_KEY_HOME, true);
context.startActivity(launchIntent);
}
/**
* This sets up a search view to use Calendar's search suggestions provider
* and to allow refining the search.
*
* @param view The {@link SearchView} to set up
* @param act The activity using the view
*/
public static void setUpSearchView(SearchView view, Activity act) {
SearchManager searchManager = (SearchManager) act.getSystemService(Context.SEARCH_SERVICE);
view.setSearchableInfo(searchManager.getSearchableInfo(act.getComponentName()));
view.setQueryRefinementEnabled(true);
}
}