code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.appwidget; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.HomeActivity; import com.google.android.apps.iosched.ui.SessionLivestreamActivity; import com.google.android.apps.iosched.util.AccountUtils; import com.google.android.apps.iosched.util.ParserUtils; import com.google.android.apps.iosched.util.UIUtils; import com.google.api.client.googleapis.extensions.android2.auth.GoogleAccountManager; import android.accounts.Account; import android.annotation.TargetApi; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.ComponentName; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.database.ContentObserver; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.widget.RemoteViews; import static com.google.android.apps.iosched.util.LogUtils.LOGV; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * The app widget's AppWidgetProvider. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class MyScheduleWidgetProvider extends AppWidgetProvider { private static final String TAG = makeLogTag(MyScheduleWidgetProvider.class); public static final String EXTRA_BLOCK_ID = "block_id"; public static final String EXTRA_STARRED_SESSION_ID = "star_session_id"; public static final String EXTRA_BLOCK_TYPE = "block_type"; public static final String EXTRA_STARRED_SESSION = "starred_session"; public static final String EXTRA_NUM_STARRED_SESSIONS = "num_starred_sessions"; public static final String EXTRA_BUTTON = "extra_button"; public static final String CLICK_ACTION = "com.google.android.apps.iosched.appwidget.action.CLICK"; public static final String REFRESH_ACTION = "com.google.android.apps.iosched.appwidget.action.REFRESH"; public static final String EXTRA_PERFORM_SYNC = "com.google.android.apps.iosched.appwidget.extra.PERFORM_SYNC"; private static Handler sWorkerQueue; // TODO: this will get destroyed when the app process is killed. need better observer strategy. private static SessionDataProviderObserver sDataObserver; public MyScheduleWidgetProvider() { // Start the worker thread HandlerThread sWorkerThread = new HandlerThread("MyScheduleWidgetProvider-worker"); sWorkerThread.start(); sWorkerQueue = new Handler(sWorkerThread.getLooper()); } @Override public void onEnabled(Context context) { final ContentResolver r = context.getContentResolver(); if (sDataObserver == null) { final AppWidgetManager mgr = AppWidgetManager.getInstance(context); final ComponentName cn = new ComponentName(context, MyScheduleWidgetProvider.class); sDataObserver = new SessionDataProviderObserver(mgr, cn, sWorkerQueue); r.registerContentObserver(ScheduleContract.Sessions.CONTENT_URI, true, sDataObserver); } } @Override public void onReceive(final Context context, Intent widgetIntent) { final String action = widgetIntent.getAction(); if (REFRESH_ACTION.equals(action)) { final boolean shouldSync = widgetIntent.getBooleanExtra(EXTRA_PERFORM_SYNC, false); sWorkerQueue.removeMessages(0); sWorkerQueue.post(new Runnable() { @Override public void run() { // Trigger sync String chosenAccountName = AccountUtils.getChosenAccountName(context); if (shouldSync && chosenAccountName != null) { Bundle extras = new Bundle(); extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); ContentResolver.requestSync( new Account(chosenAccountName, GoogleAccountManager.ACCOUNT_TYPE), ScheduleContract.CONTENT_AUTHORITY, extras); } // Update widget final AppWidgetManager mgr = AppWidgetManager.getInstance(context); final ComponentName cn = new ComponentName(context, MyScheduleWidgetProvider.class); mgr.notifyAppWidgetViewDataChanged(mgr.getAppWidgetIds(cn), R.id.widget_schedule_list); } }); } else if (CLICK_ACTION.equals(action)) { String blockId = widgetIntent.getStringExtra(EXTRA_BLOCK_ID); int numStarredSessions = widgetIntent.getIntExtra(EXTRA_NUM_STARRED_SESSIONS, 0); String starredSessionId = widgetIntent.getStringExtra(EXTRA_STARRED_SESSION_ID); String blockType = widgetIntent.getStringExtra(EXTRA_BLOCK_TYPE); boolean starredSession = widgetIntent.getBooleanExtra(EXTRA_STARRED_SESSION, false); boolean extraButton = widgetIntent.getBooleanExtra(EXTRA_BUTTON, false); LOGV(TAG, "blockId:" + blockId); LOGV(TAG, "starredSession:" + starredSession); LOGV(TAG, "blockType:" + blockType); LOGV(TAG, "numStarredSessions:" + numStarredSessions); LOGV(TAG, "extraButton:" + extraButton); if (ParserUtils.BLOCK_TYPE_SESSION.equals(blockType) || ParserUtils.BLOCK_TYPE_CODE_LAB.equals(blockType)) { Uri sessionsUri; if (numStarredSessions == 0) { sessionsUri = ScheduleContract.Blocks.buildSessionsUri( blockId); LOGV(TAG, "sessionsUri:" + sessionsUri); Intent intent = new Intent(Intent.ACTION_VIEW, sessionsUri); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } else if (numStarredSessions == 1) { if (extraButton) { sessionsUri = ScheduleContract.Blocks.buildSessionsUri(blockId); LOGV(TAG, "sessionsUri extraButton:" + sessionsUri); Intent intent = new Intent(Intent.ACTION_VIEW, sessionsUri); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } else { sessionsUri = ScheduleContract.Sessions.buildSessionUri(starredSessionId); LOGV(TAG, "sessionsUri:" + sessionsUri); Intent intent = new Intent(Intent.ACTION_VIEW, sessionsUri); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } } else { if (extraButton) { sessionsUri = ScheduleContract.Blocks.buildSessionsUri(blockId); LOGV(TAG, "sessionsUri extraButton:" + sessionsUri); Intent intent = new Intent(Intent.ACTION_VIEW, sessionsUri); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } else { sessionsUri = ScheduleContract.Blocks.buildStarredSessionsUri(blockId); LOGV(TAG, "sessionsUri:" + sessionsUri); Intent intent = new Intent(Intent.ACTION_VIEW, sessionsUri); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } } } else if (ParserUtils.BLOCK_TYPE_KEYNOTE.equals(blockType)) { Uri sessionUri = ScheduleContract.Sessions.buildSessionUri(starredSessionId); LOGV(TAG, "sessionUri:" + sessionUri); Intent intent = new Intent(Intent.ACTION_VIEW, sessionUri); intent.setClass(context, SessionLivestreamActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } } super.onReceive(context, widgetIntent); } @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { final boolean isAuthenticated = AccountUtils.isAuthenticated(context); for (int appWidgetId : appWidgetIds) { // Specify the service to provide data for the collection widget. Note that we need to // embed the appWidgetId via the data otherwise it will be ignored. final Intent intent = new Intent(context, MyScheduleWidgetService.class); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME))); final RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.widget_layout); compatSetRemoteAdapter(rv, appWidgetId, intent); // Set the empty view to be displayed if the collection is empty. It must be a sibling // view of the collection view. rv.setEmptyView(R.id.widget_schedule_list, android.R.id.empty); rv.setTextViewText(android.R.id.empty, context.getResources().getString(isAuthenticated ? R.string.empty_widget_text : R.string.empty_widget_text_signed_out)); final Intent onClickIntent = new Intent(context, MyScheduleWidgetProvider.class); onClickIntent.setAction(MyScheduleWidgetProvider.CLICK_ACTION); onClickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); onClickIntent.setData(Uri.parse(onClickIntent.toUri(Intent.URI_INTENT_SCHEME))); final PendingIntent onClickPendingIntent = PendingIntent.getBroadcast(context, 0, onClickIntent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setPendingIntentTemplate(R.id.widget_schedule_list, onClickPendingIntent); final Intent refreshIntent = new Intent(context, MyScheduleWidgetProvider.class); refreshIntent.setAction(MyScheduleWidgetProvider.REFRESH_ACTION); refreshIntent.putExtra(MyScheduleWidgetProvider.EXTRA_PERFORM_SYNC, true); final PendingIntent refreshPendingIntent = PendingIntent.getBroadcast(context, 0, refreshIntent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setOnClickPendingIntent(R.id.widget_refresh_button, refreshPendingIntent); final Intent openAppIntent = new Intent(context, HomeActivity.class); final PendingIntent openAppPendingIntent = PendingIntent.getActivity(context, 0, openAppIntent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setOnClickPendingIntent(R.id.widget_logo, openAppPendingIntent); appWidgetManager.updateAppWidget(appWidgetId, rv); } super.onUpdate(context, appWidgetManager, appWidgetIds); } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) private void compatSetRemoteAdapter(RemoteViews rv, int appWidgetId, Intent intent) { if (UIUtils.hasICS()) { rv.setRemoteAdapter(R.id.widget_schedule_list, intent); } else { //noinspection deprecation rv.setRemoteAdapter(appWidgetId, R.id.widget_schedule_list, intent); } } private static class SessionDataProviderObserver extends ContentObserver { private AppWidgetManager mAppWidgetManager; private ComponentName mComponentName; SessionDataProviderObserver(AppWidgetManager appWidgetManager, ComponentName componentName, Handler handler) { super(handler); mAppWidgetManager = appWidgetManager; mComponentName = componentName; } @Override public void onChange(boolean selfChange) { // The data has changed, so notify the widget that the collection view needs to be updated. // In response, the factory's onDataSetChanged() will be called which will requery the // cursor for the new data. mAppWidgetManager.notifyAppWidgetViewDataChanged( mAppWidgetManager.getAppWidgetIds(mComponentName), R.id.widget_schedule_list); } } }
1162584980-google-io
android/src/com/google/android/apps/iosched/appwidget/MyScheduleWidgetProvider.java
Java
asf20
13,326
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.gcm; import com.google.android.apps.iosched.BuildConfig; import com.google.android.apps.iosched.Config; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.sync.TriggerSyncReceiver; import com.google.android.apps.iosched.ui.HomeActivity; import com.google.android.apps.iosched.util.UIUtils; import com.google.android.gcm.GCMBaseIntentService; import com.google.android.gcm.GCMRegistrar; import android.app.AlarmManager; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.support.v4.app.NotificationCompat; import java.util.Random; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.LOGE; import static com.google.android.apps.iosched.util.LogUtils.LOGI; import static com.google.android.apps.iosched.util.LogUtils.LOGW; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * {@link android.app.IntentService} responsible for handling GCM messages. */ public class GCMIntentService extends GCMBaseIntentService { private static final String TAG = makeLogTag("GCM"); private static final int TRIGGER_SYNC_MAX_JITTER_MILLIS = 3 * 60 * 1000; // 3 minutes private static final Random sRandom = new Random(); public GCMIntentService() { super(Config.GCM_SENDER_ID); } @Override protected void onRegistered(Context context, String regId) { LOGI(TAG, "Device registered: regId=" + regId); ServerUtilities.register(context, regId); } @Override protected void onUnregistered(Context context, String regId) { LOGI(TAG, "Device unregistered"); if (GCMRegistrar.isRegisteredOnServer(context)) { ServerUtilities.unregister(context, regId); } else { // This callback results from the call to unregister made on // ServerUtilities when the registration to the server failed. LOGD(TAG, "Ignoring unregister callback"); } } @Override protected void onMessage(Context context, Intent intent) { if (UIUtils.isGoogleTV(context)) { // Google TV uses SyncHelper directly. return; } String announcement = intent.getStringExtra("announcement"); if (announcement != null) { displayNotification(context, announcement); return; } int jitterMillis = (int) (sRandom.nextFloat() * TRIGGER_SYNC_MAX_JITTER_MILLIS); final String debugMessage = "Received message to trigger sync; " + "jitter = " + jitterMillis + "ms"; LOGI(TAG, debugMessage); if (BuildConfig.DEBUG) { displayNotification(context, debugMessage); } ((AlarmManager) context.getSystemService(ALARM_SERVICE)) .set( AlarmManager.RTC, System.currentTimeMillis() + jitterMillis, PendingIntent.getBroadcast( context, 0, new Intent(context, TriggerSyncReceiver.class), PendingIntent.FLAG_CANCEL_CURRENT)); } private void displayNotification(Context context, String message) { LOGI(TAG, "displayNotification: " + message); ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE)) .notify(0, new NotificationCompat.Builder(context) .setWhen(System.currentTimeMillis()) .setSmallIcon(R.drawable.ic_stat_notification) .setTicker(message) .setContentTitle(context.getString(R.string.app_name)) .setContentText(message) .setContentIntent( PendingIntent.getActivity(context, 0, new Intent(context, HomeActivity.class) .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP), 0)) .setAutoCancel(true) .getNotification()); } @Override public void onError(Context context, String errorId) { LOGE(TAG, "Received error: " + errorId); } @Override protected boolean onRecoverableError(Context context, String errorId) { // log message LOGW(TAG, "Received recoverable error: " + errorId); return super.onRecoverableError(context, errorId); } }
1162584980-google-io
android/src/com/google/android/apps/iosched/gcm/GCMIntentService.java
Java
asf20
5,422
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.gcm; import com.google.android.apps.iosched.Config; import com.google.android.gcm.GCMRegistrar; import android.content.Context; import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.LOGE; import static com.google.android.apps.iosched.util.LogUtils.LOGI; import static com.google.android.apps.iosched.util.LogUtils.LOGV; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * Helper class used to communicate with the demo server. */ public final class ServerUtilities { private static final String TAG = makeLogTag("GCM"); private static final int MAX_ATTEMPTS = 5; private static final int BACKOFF_MILLIS = 2000; private static final Random sRandom = new Random(); /** * Register this account/device pair within the server. * * @param context Current context * @param regId The GCM registration ID for this device * @return whether the registration succeeded or not. */ public static boolean register(final Context context, final String regId) { LOGI(TAG, "registering device (regId = " + regId + ")"); String serverUrl = Config.GCM_SERVER_URL + "/register"; Map<String, String> params = new HashMap<String, String>(); params.put("regId", regId); long backoff = BACKOFF_MILLIS + sRandom.nextInt(1000); // Once GCM returns a registration id, we need to register it in the // demo server. As the server might be down, we will retry it a couple // times. for (int i = 1; i <= MAX_ATTEMPTS; i++) { LOGV(TAG, "Attempt #" + i + " to register"); try { post(serverUrl, params); GCMRegistrar.setRegisteredOnServer(context, true); return true; } catch (IOException e) { // Here we are simplifying and retrying on any error; in a real // application, it should retry only on unrecoverable errors // (like HTTP error code 503). LOGE(TAG, "Failed to register on attempt " + i, e); if (i == MAX_ATTEMPTS) { break; } try { LOGV(TAG, "Sleeping for " + backoff + " ms before retry"); Thread.sleep(backoff); } catch (InterruptedException e1) { // Activity finished before we complete - exit. LOGD(TAG, "Thread interrupted: abort remaining retries!"); Thread.currentThread().interrupt(); return false; } // increase backoff exponentially backoff *= 2; } } return false; } /** * Unregister this account/device pair within the server. * * @param context Current context * @param regId The GCM registration ID for this device */ static void unregister(final Context context, final String regId) { LOGI(TAG, "unregistering device (regId = " + regId + ")"); String serverUrl = Config.GCM_SERVER_URL + "/unregister"; Map<String, String> params = new HashMap<String, String>(); params.put("regId", regId); try { post(serverUrl, params); GCMRegistrar.setRegisteredOnServer(context, false); } catch (IOException e) { // At this point the device is unregistered from GCM, but still // registered in the server. // We could try to unregister again, but it is not necessary: // if the server tries to send a message to the device, it will get // a "NotRegistered" error message and should unregister the device. LOGD(TAG, "Unable to unregister from application server", e); } } /** * Issue a POST request to the server. * * @param endpoint POST address. * @param params request parameters. * @throws java.io.IOException propagated from POST. */ private static void post(String endpoint, Map<String, String> params) throws IOException { URL url; try { url = new URL(endpoint); } catch (MalformedURLException e) { throw new IllegalArgumentException("invalid url: " + endpoint); } StringBuilder bodyBuilder = new StringBuilder(); Iterator<Entry<String, String>> iterator = params.entrySet().iterator(); // constructs the POST body using the parameters while (iterator.hasNext()) { Entry<String, String> param = iterator.next(); bodyBuilder.append(param.getKey()).append('=') .append(param.getValue()); if (iterator.hasNext()) { bodyBuilder.append('&'); } } String body = bodyBuilder.toString(); LOGV(TAG, "Posting '" + body + "' to " + url); HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setChunkedStreamingMode(0); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); conn.setRequestProperty("Content-Length", Integer.toString(body.length())); // post the request OutputStream out = conn.getOutputStream(); out.write(body.getBytes()); out.close(); // handle the response int status = conn.getResponseCode(); if (status != 200) { throw new IOException("Post failed with error code " + status); } } finally { if (conn != null) { conn.disconnect(); } } } }
1162584980-google-io
android/src/com/google/android/apps/iosched/gcm/ServerUtilities.java
Java
asf20
6,922
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.gcm; import com.google.android.gcm.GCMBroadcastReceiver; import android.content.Context; /** * @author trevorjohns@google.com (Trevor Johns) */ public class GCMRedirectedBroadcastReceiver extends GCMBroadcastReceiver { /** * Gets the class name of the intent service that will handle GCM messages. * * Used to override class name, so that GCMIntentService can live in a * subpackage. */ @Override protected String getGCMIntentServiceClassName(Context context) { return GCMIntentService.class.getCanonicalName(); } }
1162584980-google-io
android/src/com/google/android/apps/iosched/gcm/GCMRedirectedBroadcastReceiver.java
Java
asf20
1,209
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.sync; import com.google.android.apps.iosched.BuildConfig; import com.google.android.apps.iosched.util.AccountUtils; import android.accounts.Account; import android.content.AbstractThreadedSyncAdapter; import android.content.ContentProviderClient; import android.content.ContentResolver; import android.content.Context; import android.content.SyncResult; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.widget.Toast; import java.io.IOException; import java.util.regex.Pattern; import static com.google.android.apps.iosched.util.LogUtils.LOGE; import static com.google.android.apps.iosched.util.LogUtils.LOGI; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * Sync adapter for Google I/O data. Note that this sync adapter makes heavy use of a * "conference API" that is not currently open source. */ public class SyncAdapter extends AbstractThreadedSyncAdapter { private static final String TAG = makeLogTag(SyncAdapter.class); private static final Pattern sSanitizeAccountNamePattern = Pattern.compile("(.).*?(.?)@"); private final Context mContext; private SyncHelper mSyncHelper; public SyncAdapter(Context context, boolean autoInitialize) { super(context, autoInitialize); mContext = context; //noinspection ConstantConditions,PointlessBooleanExpression if (!BuildConfig.DEBUG) { Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread thread, Throwable throwable) { LOGE(TAG, "Uncaught sync exception, suppressing UI in release build.", throwable); } }); } } @Override public void onPerformSync(final Account account, Bundle extras, String authority, final ContentProviderClient provider, final SyncResult syncResult) { final boolean uploadOnly = extras.getBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, false); final boolean manualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false); final boolean initialize = extras.getBoolean(ContentResolver.SYNC_EXTRAS_INITIALIZE, false); final String logSanitizedAccountName = sSanitizeAccountNamePattern .matcher(account.name).replaceAll("$1...$2@"); if (uploadOnly) { return; } LOGI(TAG, "Beginning sync for account " + logSanitizedAccountName + "," + " uploadOnly=" + uploadOnly + " manualSync=" + manualSync + " initialize=" + initialize); if (initialize) { String chosenAccountName = AccountUtils.getChosenAccountName(mContext); boolean isChosenAccount = chosenAccountName != null && chosenAccountName.equals(account.name); ContentResolver.setIsSyncable(account, authority, isChosenAccount ? 1 : 0); if (!isChosenAccount) { ++syncResult.stats.numAuthExceptions; return; } } // Perform a sync using SyncHelper if (mSyncHelper == null) { mSyncHelper = new SyncHelper(mContext); } try { mSyncHelper.performSync(syncResult, SyncHelper.FLAG_SYNC_LOCAL | SyncHelper.FLAG_SYNC_REMOTE); } catch (IOException e) { ++syncResult.stats.numIoExceptions; LOGE(TAG, "Error syncing data for I/O 2012.", e); } } }
1162584980-google-io
android/src/com/google/android/apps/iosched/sync/SyncAdapter.java
Java
asf20
4,247
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.sync; import com.google.android.apps.iosched.io.HandlerException; import android.app.Service; import android.content.Intent; import android.os.Handler; import android.os.HandlerThread; import android.os.IBinder; import android.os.Looper; import android.os.Message; import android.widget.Toast; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import static com.google.android.apps.iosched.util.LogUtils.LOGE; import static com.google.android.apps.iosched.util.LogUtils.LOGI; import static com.google.android.apps.iosched.util.LogUtils.LOGW; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * Background {@link android.app.Service} that adds or removes sessions from your calendar via the * Conference API. * * @see com.google.android.apps.iosched.sync.SyncHelper */ public class ScheduleUpdaterService extends Service { private static final String TAG = makeLogTag(ScheduleUpdaterService.class); public static final String EXTRA_SESSION_ID = "com.google.android.apps.iosched.extra.SESSION_ID"; public static final String EXTRA_IN_SCHEDULE = "com.google.android.apps.iosched.extra.IN_SCHEDULE"; private static final int SCHEDULE_UPDATE_DELAY_MILLIS = 5000; private final Handler mUiThreadHandler = new Handler(); private volatile Looper mServiceLooper; private volatile ServiceHandler mServiceHandler; private final LinkedList<Intent> mScheduleUpdates = new LinkedList<Intent>(); // Handler pattern copied from IntentService private final class ServiceHandler extends Handler { public ServiceHandler(Looper looper) { super(looper); } @Override public void handleMessage(Message msg) { processPendingScheduleUpdates(); int numRemainingUpdates; synchronized (mScheduleUpdates) { numRemainingUpdates = mScheduleUpdates.size(); } if (numRemainingUpdates == 0) { stopSelf(); } else { // More updates were added since the current pending set was processed. Reschedule // another pass. removeMessages(0); sendEmptyMessageDelayed(0, SCHEDULE_UPDATE_DELAY_MILLIS); } } } public ScheduleUpdaterService() { } @Override public void onCreate() { super.onCreate(); HandlerThread thread = new HandlerThread(ScheduleUpdaterService.class.getSimpleName()); thread.start(); mServiceLooper = thread.getLooper(); mServiceHandler = new ServiceHandler(mServiceLooper); } @Override public int onStartCommand(Intent intent, int flags, int startId) { // When receiving a new intent, delay the schedule until 5 seconds from now. mServiceHandler.removeMessages(0); mServiceHandler.sendEmptyMessageDelayed(0, SCHEDULE_UPDATE_DELAY_MILLIS); // Remove pending updates involving this session ID. String sessionId = intent.getStringExtra(EXTRA_SESSION_ID); Iterator<Intent> updatesIterator = mScheduleUpdates.iterator(); while (updatesIterator.hasNext()) { Intent existingIntent = updatesIterator.next(); if (sessionId.equals(existingIntent.getStringExtra(EXTRA_SESSION_ID))) { updatesIterator.remove(); } } // Queue this schedule update. synchronized (mScheduleUpdates) { mScheduleUpdates.add(intent); } return START_REDELIVER_INTENT; } @Override public void onDestroy() { mServiceLooper.quit(); } @Override public IBinder onBind(Intent intent) { return null; } public void processPendingScheduleUpdates() { try { // Operate on a local copy of the schedule update list so as not to block // the main thread adding to this list List<Intent> scheduleUpdates = new ArrayList<Intent>(); synchronized (mScheduleUpdates) { scheduleUpdates.addAll(mScheduleUpdates); mScheduleUpdates.clear(); } SyncHelper syncHelper = new SyncHelper(this); for (Intent updateIntent : scheduleUpdates) { String sessionId = updateIntent.getStringExtra(EXTRA_SESSION_ID); boolean inSchedule = updateIntent.getBooleanExtra(EXTRA_IN_SCHEDULE, false); LOGI(TAG, "addOrRemoveSessionFromSchedule:" + " sessionId=" + sessionId + " inSchedule=" + inSchedule); syncHelper.addOrRemoveSessionFromSchedule(this, sessionId, inSchedule); } } catch (HandlerException.NoDevsiteProfileException e) { // The user doesn't have a profile, message this to them. // TODO: better UX for this type of error LOGW(TAG, "To sync your schedule to the web, login to developers.google.com.", e); mUiThreadHandler.post(new Runnable() { @Override public void run() { Toast.makeText(ScheduleUpdaterService.this, "To sync your schedule to the web, login to developers.google.com.", Toast.LENGTH_LONG).show(); } }); } catch (IOException e) { // TODO: do something useful here, like revert the changes locally in the // content provider to maintain client/server sync LOGE(TAG, "Error processing schedule update", e); } } }
1162584980-google-io
android/src/com/google/android/apps/iosched/sync/ScheduleUpdaterService.java
Java
asf20
6,382
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.sync; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.Config; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.io.AnnouncementsHandler; import com.google.android.apps.iosched.io.BlocksHandler; import com.google.android.apps.iosched.io.HandlerException; import com.google.android.apps.iosched.io.JSONHandler; import com.google.android.apps.iosched.io.RoomsHandler; import com.google.android.apps.iosched.io.SandboxHandler; import com.google.android.apps.iosched.io.SearchSuggestHandler; import com.google.android.apps.iosched.io.SessionsHandler; import com.google.android.apps.iosched.io.SpeakersHandler; import com.google.android.apps.iosched.io.TracksHandler; import com.google.android.apps.iosched.io.model.EditMyScheduleResponse; import com.google.android.apps.iosched.io.model.ErrorResponse; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.calendar.SessionCalendarService; import com.google.android.apps.iosched.util.AccountUtils; import com.google.android.apps.iosched.util.UIUtils; import com.google.api.client.googleapis.extensions.android2.auth.GoogleAccountManager; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.JsonSyntaxException; import android.accounts.Account; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.OperationApplicationException; import android.content.SharedPreferences; import android.content.SyncResult; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.database.Cursor; import android.net.ConnectivityManager; import android.os.RemoteException; import android.preference.PreferenceManager; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.LOGI; import static com.google.android.apps.iosched.util.LogUtils.LOGV; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * A helper class for dealing with sync and other remote persistence operations. * All operations occur on the thread they're called from, so it's best to wrap * calls in an {@link android.os.AsyncTask}, or better yet, a * {@link android.app.Service}. */ public class SyncHelper { private static final String TAG = makeLogTag(SyncHelper.class); static { // Per http://android-developers.blogspot.com/2011/09/androids-http-clients.html if (!UIUtils.hasFroyo()) { System.setProperty("http.keepAlive", "false"); } } public static final int FLAG_SYNC_LOCAL = 0x1; public static final int FLAG_SYNC_REMOTE = 0x2; private static final int LOCAL_VERSION_CURRENT = 19; private Context mContext; private String mAuthToken; private String mUserAgent; public SyncHelper(Context context) { mContext = context; mUserAgent = buildUserAgent(context); } /** * Loads conference information (sessions, rooms, tracks, speakers, etc.) * from a local static cache data and then syncs down data from the * Conference API. * * @param syncResult Optional {@link SyncResult} object to populate. * @throws IOException */ public void performSync(SyncResult syncResult, int flags) throws IOException { mAuthToken = AccountUtils.getAuthToken(mContext); final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext); final int localVersion = prefs.getInt("local_data_version", 0); // Bulk of sync work, performed by executing several fetches from // local and online sources. final ContentResolver resolver = mContext.getContentResolver(); ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>(); LOGI(TAG, "Performing sync"); if ((flags & FLAG_SYNC_LOCAL) != 0) { final long startLocal = System.currentTimeMillis(); final boolean localParse = localVersion < LOCAL_VERSION_CURRENT; LOGD(TAG, "found localVersion=" + localVersion + " and LOCAL_VERSION_CURRENT=" + LOCAL_VERSION_CURRENT); // Only run local sync if there's a newer version of data available // than what was last locally-sync'd. if (localParse) { // Load static local data batch.addAll(new RoomsHandler(mContext).parse( JSONHandler.loadResourceJson(mContext, R.raw.rooms))); batch.addAll(new BlocksHandler(mContext).parse( JSONHandler.loadResourceJson(mContext, R.raw.common_slots))); batch.addAll(new TracksHandler(mContext).parse( JSONHandler.loadResourceJson(mContext, R.raw.tracks))); batch.addAll(new SpeakersHandler(mContext, true).parse( JSONHandler.loadResourceJson(mContext, R.raw.speakers))); batch.addAll(new SessionsHandler(mContext, true, false).parse( JSONHandler.loadResourceJson(mContext, R.raw.sessions))); batch.addAll(new SandboxHandler(mContext, true).parse( JSONHandler.loadResourceJson(mContext, R.raw.sandbox))); batch.addAll(new SearchSuggestHandler(mContext).parse( JSONHandler.loadResourceJson(mContext, R.raw.search_suggest))); prefs.edit().putInt("local_data_version", LOCAL_VERSION_CURRENT).commit(); if (syncResult != null) { ++syncResult.stats.numUpdates; ++syncResult.stats.numEntries; } } LOGD(TAG, "Local sync took " + (System.currentTimeMillis() - startLocal) + "ms"); try { // Apply all queued up batch operations for local data. resolver.applyBatch(ScheduleContract.CONTENT_AUTHORITY, batch); } catch (RemoteException e) { throw new RuntimeException("Problem applying batch operation", e); } catch (OperationApplicationException e) { throw new RuntimeException("Problem applying batch operation", e); } batch = new ArrayList<ContentProviderOperation>(); } if ((flags & FLAG_SYNC_REMOTE) != 0 && isOnline()) { try { boolean auth = !UIUtils.isGoogleTV(mContext) && AccountUtils.isAuthenticated(mContext); final long startRemote = System.currentTimeMillis(); LOGI(TAG, "Remote syncing speakers"); batch.addAll(executeGet(Config.GET_ALL_SPEAKERS_URL, new SpeakersHandler(mContext, false), auth)); LOGI(TAG, "Remote syncing sessions"); batch.addAll(executeGet(Config.GET_ALL_SESSIONS_URL, new SessionsHandler(mContext, false, mAuthToken != null), auth)); LOGI(TAG, "Remote syncing sandbox"); batch.addAll(executeGet(Config.GET_SANDBOX_URL, new SandboxHandler(mContext, false), auth)); LOGI(TAG, "Remote syncing announcements"); batch.addAll(executeGet(Config.GET_ALL_ANNOUNCEMENTS_URL, new AnnouncementsHandler(mContext, false), auth)); // GET_ALL_SESSIONS covers the functionality GET_MY_SCHEDULE provides here. LOGD(TAG, "Remote sync took " + (System.currentTimeMillis() - startRemote) + "ms"); if (syncResult != null) { ++syncResult.stats.numUpdates; ++syncResult.stats.numEntries; } EasyTracker.getTracker().dispatch(); } catch (HandlerException.UnauthorizedException e) { LOGI(TAG, "Unauthorized; getting a new auth token.", e); if (syncResult != null) { ++syncResult.stats.numAuthExceptions; } AccountUtils.invalidateAuthToken(mContext); AccountUtils.tryAuthenticateWithErrorNotification(mContext, null, new Account(AccountUtils.getChosenAccountName(mContext), GoogleAccountManager.ACCOUNT_TYPE)); } // all other IOExceptions are thrown } try { // Apply all queued up remaining batch operations (only remote content at this point). resolver.applyBatch(ScheduleContract.CONTENT_AUTHORITY, batch); // Delete empty blocks Cursor emptyBlocksCursor = resolver.query(ScheduleContract.Blocks.CONTENT_URI, new String[]{ScheduleContract.Blocks.BLOCK_ID,ScheduleContract.Blocks.SESSIONS_COUNT}, ScheduleContract.Blocks.EMPTY_SESSIONS_SELECTION, null, null); batch = new ArrayList<ContentProviderOperation>(); int numDeletedEmptyBlocks = 0; while (emptyBlocksCursor.moveToNext()) { batch.add(ContentProviderOperation .newDelete(ScheduleContract.Blocks.buildBlockUri( emptyBlocksCursor.getString(0))) .build()); ++numDeletedEmptyBlocks; } emptyBlocksCursor.close(); resolver.applyBatch(ScheduleContract.CONTENT_AUTHORITY, batch); LOGD(TAG, "Deleted " + numDeletedEmptyBlocks + " empty session blocks."); } catch (RemoteException e) { throw new RuntimeException("Problem applying batch operation", e); } catch (OperationApplicationException e) { throw new RuntimeException("Problem applying batch operation", e); } if (UIUtils.hasICS()) { LOGD(TAG, "Done with sync'ing conference data. Starting to sync " + "session with Calendar."); syncCalendar(); } } private void syncCalendar() { Intent intent = new Intent(SessionCalendarService.ACTION_UPDATE_ALL_SESSIONS_CALENDAR); intent.setClass(mContext, SessionCalendarService.class); mContext.startService(intent); } /** * Build and return a user-agent string that can identify this application * to remote servers. Contains the package name and version code. */ private static String buildUserAgent(Context context) { String versionName = "unknown"; int versionCode = 0; try { final PackageInfo info = context.getPackageManager() .getPackageInfo(context.getPackageName(), 0); versionName = info.versionName; versionCode = info.versionCode; } catch (PackageManager.NameNotFoundException ignored) { } return context.getPackageName() + "/" + versionName + " (" + versionCode + ") (gzip)"; } public void addOrRemoveSessionFromSchedule(Context context, String sessionId, boolean inSchedule) throws IOException { mAuthToken = AccountUtils.getAuthToken(mContext); JsonObject starredSession = new JsonObject(); starredSession.addProperty("sessionid", sessionId); byte[] postJsonBytes = new Gson().toJson(starredSession).getBytes(); URL url = new URL(Config.EDIT_MY_SCHEDULE_URL + (inSchedule ? "add" : "remove")); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("User-Agent", mUserAgent); urlConnection.setRequestProperty("Content-Type", "application/json"); urlConnection.setRequestProperty("Authorization", "Bearer " + mAuthToken); urlConnection.setDoOutput(true); urlConnection.setFixedLengthStreamingMode(postJsonBytes.length); LOGD(TAG, "Posting to URL: " + url); OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream()); out.write(postJsonBytes); out.flush(); urlConnection.connect(); throwErrors(urlConnection); String json = readInputStream(urlConnection.getInputStream()); EditMyScheduleResponse response = new Gson().fromJson(json, EditMyScheduleResponse.class); if (!response.success) { String responseMessageLower = (response.message != null) ? response.message.toLowerCase() : ""; if (responseMessageLower.contains("no profile")) { throw new HandlerException.NoDevsiteProfileException(); } } } private ArrayList<ContentProviderOperation> executeGet(String urlString, JSONHandler handler, boolean authenticated) throws IOException { LOGD(TAG, "Requesting URL: " + urlString); URL url = new URL(urlString); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("User-Agent", mUserAgent); if (authenticated && mAuthToken != null) { urlConnection.setRequestProperty("Authorization", "Bearer " + mAuthToken); } urlConnection.connect(); throwErrors(urlConnection); String response = readInputStream(urlConnection.getInputStream()); LOGV(TAG, "HTTP response: " + response); return handler.parse(response); } private void throwErrors(HttpURLConnection urlConnection) throws IOException { final int status = urlConnection.getResponseCode(); if (status < 200 || status >= 300) { String errorMessage = null; try { String errorContent = readInputStream(urlConnection.getErrorStream()); LOGV(TAG, "Error content: " + errorContent); ErrorResponse errorResponse = new Gson().fromJson( errorContent, ErrorResponse.class); errorMessage = errorResponse.error.message; } catch (IOException ignored) { } catch (JsonSyntaxException ignored) { } String exceptionMessage = "Error response " + status + " " + urlConnection.getResponseMessage() + (errorMessage == null ? "" : (": " + errorMessage)) + " for " + urlConnection.getURL(); // TODO: the API should return 401, and we shouldn't have to parse the message throw (errorMessage != null && errorMessage.toLowerCase().contains("auth")) ? new HandlerException.UnauthorizedException(exceptionMessage) : new HandlerException(exceptionMessage); } } private static String readInputStream(InputStream inputStream) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String responseLine; StringBuilder responseBuilder = new StringBuilder(); while ((responseLine = bufferedReader.readLine()) != null) { responseBuilder.append(responseLine); } return responseBuilder.toString(); } private boolean isOnline() { ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService( Context.CONNECTIVITY_SERVICE); return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnectedOrConnecting(); } }
1162584980-google-io
android/src/com/google/android/apps/iosched/sync/SyncHelper.java
Java
asf20
16,614
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.sync; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.AccountUtils; import com.google.api.client.googleapis.extensions.android2.auth.GoogleAccountManager; import android.accounts.Account; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; /** * A simple {@link BroadcastReceiver} that triggers a sync. This is used by the GCM code to trigger * jittered syncs using {@link android.app.AlarmManager}. */ public class TriggerSyncReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String accountName = AccountUtils.getChosenAccountName(context); if (TextUtils.isEmpty(accountName)) { return; } ContentResolver.requestSync( new Account(accountName, GoogleAccountManager.ACCOUNT_TYPE), ScheduleContract.CONTENT_AUTHORITY, new Bundle()); } }
1162584980-google-io
android/src/com/google/android/apps/iosched/sync/TriggerSyncReceiver.java
Java
asf20
1,733
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.sync; import android.app.Service; import android.content.Intent; import android.os.IBinder; /** * Service that handles sync. It simply instantiates a SyncAdapter and returns its IBinder. */ public class SyncService extends Service { private static final Object sSyncAdapterLock = new Object(); private static SyncAdapter sSyncAdapter = null; @Override public void onCreate() { synchronized (sSyncAdapterLock) { if (sSyncAdapter == null) { sSyncAdapter = new SyncAdapter(getApplicationContext(), false); } } } @Override public IBinder onBind(Intent intent) { return sSyncAdapter.getSyncAdapterBinder(); } }
1162584980-google-io
android/src/com/google/android/apps/iosched/sync/SyncService.java
Java
asf20
1,345
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched; public class Config { // OAuth 2.0 related config public static final String APP_NAME = "Your-App-Name"; public static final String API_KEY = "API_KEY"; // from the APIs console public static final String CLIENT_ID = "0000000000000.apps.googleusercontent.com"; // from the APIs console // Conference API-specific config // NOTE: the backend used for the Google I/O 2012 Android app is not currently open source, so // you should modify these fields to reflect your own backend. private static final String CONFERENCE_API_KEY = "API_KEY"; private static final String ROOT_EVENT_ID = "googleio2012"; private static final String BASE_URL = "https://google-developers.appspot.com/_ah/api/resources/v0.1"; public static final String GET_ALL_SESSIONS_URL = BASE_URL + "/sessions?parent_event=" + ROOT_EVENT_ID + "&api_key=" + CONFERENCE_API_KEY; public static final String GET_ALL_SPEAKERS_URL = BASE_URL + "/speakers?event_id=" + ROOT_EVENT_ID + "&api_key=" + CONFERENCE_API_KEY; public static final String GET_ALL_ANNOUNCEMENTS_URL = BASE_URL + "/announcements?parent_event=" + ROOT_EVENT_ID + "&api_key=" + CONFERENCE_API_KEY; public static final String EDIT_MY_SCHEDULE_URL = BASE_URL + "/editmyschedule/o/"; // Static file host for the sandbox data public static final String GET_SANDBOX_URL = "https://developers.google.com/events/io/sandbox-data"; // YouTube API config public static final String YOUTUBE_API_KEY = "API_KEY"; // YouTube share URL public static final String YOUTUBE_SHARE_URL_PREFIX = "http://youtu.be/"; // Livestream captions config public static final String PRIMARY_LIVESTREAM_CAPTIONS_URL = "TODO"; public static final String SECONDARY_LIVESTREAM_CAPTIONS_URL = "TODO"; public static final String PRIMARY_LIVESTREAM_TRACK = "android"; public static final String SECONDARY_LIVESTREAM_TRACK = "chrome"; // GCM config public static final String GCM_SERVER_URL = "https://yourapp-gcm.appspot.com"; public static final String GCM_SENDER_ID = "0000000000000"; // project ID from the APIs console }
1162584980-google-io
android/src/com/google/android/apps/iosched/Config.java
Java
asf20
2,785
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.actionbarsherlock.app.SherlockFragment; import android.app.Activity; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; /** * A retained, non-UI helper fragment that loads track information such as name, color, etc. and * returns this information via {@link Callbacks#onTrackInfoAvailable(String, String, int)}. */ public class TrackInfoHelperFragment extends SherlockFragment implements LoaderManager.LoaderCallbacks<Cursor> { /** * The track URI for which to load data. */ public static final String ARG_TRACK = "com.google.android.iosched.extra.TRACK"; private Uri mTrackUri; // To be loaded private String mTrackId; private String mTrackName; private int mTrackColor; private Handler mHandler = new Handler(); public interface Callbacks { public void onTrackInfoAvailable(String trackId, String trackName, int trackColor); } private static Callbacks sDummyCallbacks = new Callbacks() { @Override public void onTrackInfoAvailable(String trackId, String trackName, int trackColor) { } }; private Callbacks mCallbacks = sDummyCallbacks; public static TrackInfoHelperFragment newFromSessionUri(Uri sessionUri) { return newFromTrackUri(ScheduleContract.Sessions.buildTracksDirUri( ScheduleContract.Sessions.getSessionId(sessionUri))); } public static TrackInfoHelperFragment newFromTrackUri(Uri trackUri) { TrackInfoHelperFragment f = new TrackInfoHelperFragment(); Bundle args = new Bundle(); args.putParcelable(ARG_TRACK, trackUri); f.setArguments(args); return f; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); mTrackUri = getArguments().getParcelable(ARG_TRACK); if (ScheduleContract.Tracks.ALL_TRACK_ID.equals( ScheduleContract.Tracks.getTrackId(mTrackUri))) { mTrackId = ScheduleContract.Tracks.ALL_TRACK_ID; mTrackName = getString(R.string.all_tracks); mTrackColor = getResources().getColor(android.R.color.white); mCallbacks.onTrackInfoAvailable(mTrackId, mTrackName, mTrackColor); } else { getLoaderManager().initLoader(0, null, this); } } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (!(activity instanceof Callbacks)) { throw new ClassCastException("Activity must implement fragment's callbacks."); } mCallbacks = (Callbacks) activity; if (mTrackId != null) { mHandler.post(new Runnable() { @Override public void run() { mCallbacks.onTrackInfoAvailable(mTrackId, mTrackName, mTrackColor); } }); } } @Override public void onDetach() { super.onDetach(); mCallbacks = sDummyCallbacks; } @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { return new CursorLoader(getActivity(), mTrackUri, TracksQuery.PROJECTION, null, null, null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { try { if (!cursor.moveToFirst()) { return; } mTrackId = cursor.getString(TracksQuery.TRACK_ID); mTrackName = cursor.getString(TracksQuery.TRACK_NAME); mTrackColor = cursor.getInt(TracksQuery.TRACK_COLOR); // Wrapping in a Handler.post allows users of this helper to commit fragment // transactions in the callback. new Handler().post(new Runnable() { @Override public void run() { mCallbacks.onTrackInfoAvailable(mTrackId, mTrackName, mTrackColor); } }); } finally { cursor.close(); } } @Override public void onLoaderReset(Loader<Cursor> loader) { } /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Tracks} query parameters. */ private interface TracksQuery { String[] PROJECTION = { ScheduleContract.Tracks.TRACK_ID, ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Tracks.TRACK_COLOR, }; int TRACK_ID = 0; int TRACK_NAME = 1; int TRACK_COLOR = 2; } }
1162584980-google-io
android/src/com/google/android/apps/iosched/ui/TrackInfoHelperFragment.java
Java
asf20
5,505
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.tablet.SessionsVendorsMultiPaneActivity; import com.google.android.apps.iosched.ui.widget.SimpleSectionedListAdapter; import com.google.android.apps.iosched.util.ParserUtils; import com.google.android.apps.iosched.util.SessionsHelper; import com.google.android.apps.iosched.util.UIUtils; import com.google.android.apps.iosched.util.actionmodecompat.ActionMode; import com.actionbarsherlock.app.SherlockListFragment; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.database.ContentObserver; import android.database.Cursor; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.provider.BaseColumns; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.text.TextUtils; import android.text.format.DateUtils; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnLongClickListener; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.ImageButton; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import static com.google.android.apps.iosched.util.LogUtils.LOGW; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * A fragment that shows the user's customized schedule, including sessions that she has chosen, * and common conference items such as keynote sessions, lunch breaks, after hours party, etc. */ public class MyScheduleFragment extends SherlockListFragment implements LoaderManager.LoaderCallbacks<Cursor>, ActionMode.Callback { private static final String TAG = makeLogTag(MyScheduleFragment.class); private SimpleSectionedListAdapter mAdapter; private MyScheduleAdapter mScheduleAdapter; private SparseArray<String> mLongClickedItemData; private View mLongClickedView; private ActionMode mActionMode; private boolean mScrollToNow; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // The MyScheduleAdapter is wrapped in a SimpleSectionedListAdapter so that // we can show list headers separating out the different days of the conference // (Wednesday/Thursday/Friday). mScheduleAdapter = new MyScheduleAdapter(getActivity()); mAdapter = new SimpleSectionedListAdapter(getActivity(), R.layout.list_item_schedule_header, mScheduleAdapter); setListAdapter(mAdapter); if (savedInstanceState == null) { mScrollToNow = true; } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup root = (ViewGroup) inflater.inflate( R.layout.fragment_list_with_empty_container, container, false); inflater.inflate(R.layout.empty_waiting_for_sync, (ViewGroup) root.findViewById(android.R.id.empty), true); root.setBackgroundColor(Color.WHITE); ListView listView = (ListView) root.findViewById(android.R.id.list); listView.setItemsCanFocus(true); listView.setCacheColorHint(Color.WHITE); listView.setSelector(android.R.color.transparent); //listView.setEmptyView(root.findViewById(android.R.id.empty)); return root; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // In support library r8, calling initLoader for a fragment in a // FragmentPagerAdapter in the fragment's onCreate may cause the same LoaderManager to be // dealt to multiple fragments because their mIndex is -1 (haven't been added to the // activity yet). Thus, we do this in onActivityCreated. getLoaderManager().initLoader(0, null, this); } private final ContentObserver mObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { if (getActivity() == null) { return; } Loader<Cursor> loader = getLoaderManager().getLoader(0); if (loader != null) { loader.forceLoad(); } } }; @Override public void onAttach(Activity activity) { super.onAttach(activity); activity.getContentResolver().registerContentObserver( ScheduleContract.Sessions.CONTENT_URI, true, mObserver); } @Override public void onDetach() { super.onDetach(); getActivity().getContentResolver().unregisterContentObserver(mObserver); } // LoaderCallbacks @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { return new CursorLoader(getActivity(), ScheduleContract.Blocks.CONTENT_URI, BlocksQuery.PROJECTION, null, null, ScheduleContract.Blocks.DEFAULT_SORT); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if (getActivity() == null) { return; } long currentTime = UIUtils.getCurrentTime(getActivity()); int firstNowPosition = ListView.INVALID_POSITION; List<SimpleSectionedListAdapter.Section> sections = new ArrayList<SimpleSectionedListAdapter.Section>(); cursor.moveToFirst(); long previousBlockStart = -1; long blockStart, blockEnd; while (!cursor.isAfterLast()) { blockStart = cursor.getLong(BlocksQuery.BLOCK_START); blockEnd = cursor.getLong(BlocksQuery.BLOCK_END); if (!UIUtils.isSameDay(previousBlockStart, blockStart)) { sections.add(new SimpleSectionedListAdapter.Section(cursor.getPosition(), DateUtils.formatDateTime(getActivity(), blockStart, DateUtils.FORMAT_ABBREV_MONTH | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY))); } if (mScrollToNow && firstNowPosition == ListView.INVALID_POSITION // if we're currently in this block, or we're not in a block // and this // block is in the future, then this is the scroll position && ((blockStart < currentTime && currentTime < blockEnd) || blockStart > currentTime)) { firstNowPosition = cursor.getPosition(); } previousBlockStart = blockStart; cursor.moveToNext(); } mScheduleAdapter.changeCursor(cursor); SimpleSectionedListAdapter.Section[] dummy = new SimpleSectionedListAdapter.Section[sections.size()]; mAdapter.setSections(sections.toArray(dummy)); if (mScrollToNow && firstNowPosition != ListView.INVALID_POSITION) { firstNowPosition = mAdapter.positionToSectionedPosition(firstNowPosition); getListView().setSelectionFromTop(firstNowPosition, getResources().getDimensionPixelSize(R.dimen.list_scroll_top_offset)); mScrollToNow = false; } } @Override public void onLoaderReset(Loader<Cursor> loader) { } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { SessionsHelper helper = new SessionsHelper(getActivity()); String title = mLongClickedItemData.get(BlocksQuery.STARRED_SESSION_TITLE); String hashtags = mLongClickedItemData.get(BlocksQuery.STARRED_SESSION_HASHTAGS); String url = mLongClickedItemData.get(BlocksQuery.STARRED_SESSION_URL); boolean handled = false; switch (item.getItemId()) { case R.id.menu_map: String roomId = mLongClickedItemData.get(BlocksQuery.STARRED_SESSION_ROOM_ID); helper.startMapActivity(roomId); handled = true; break; case R.id.menu_star: String sessionId = mLongClickedItemData.get(BlocksQuery.STARRED_SESSION_ID); Uri sessionUri = ScheduleContract.Sessions.buildSessionUri(sessionId); helper.setSessionStarred(sessionUri, false, title); handled = true; break; case R.id.menu_share: // On ICS+ devices, we normally won't reach this as ShareActionProvider will handle // sharing. helper.shareSession(getActivity(), R.string.share_template, title, hashtags, url); handled = true; break; case R.id.menu_social_stream: helper.startSocialStream(hashtags); handled = true; break; default: LOGW(TAG, "Unknown action taken"); } mActionMode.finish(); return handled; } @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { MenuInflater inflater = mode.getMenuInflater(); inflater.inflate(R.menu.sessions_context, menu); MenuItem starMenuItem = menu.findItem(R.id.menu_star); starMenuItem.setTitle(R.string.description_remove_schedule); starMenuItem.setIcon(R.drawable.ic_action_remove_schedule); return true; } @Override public void onDestroyActionMode(ActionMode mode) { mActionMode = null; if (mLongClickedView != null) { UIUtils.setActivatedCompat(mLongClickedView, false); } } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return false; } /** * A list adapter that shows schedule blocks as list items. It handles a number of different * cases, such as empty blocks where the user has not chosen a session, blocks with conflicts * (i.e. multiple sessions chosen), non-session blocks, etc. */ private class MyScheduleAdapter extends CursorAdapter { public MyScheduleAdapter(Context context) { super(context, null, false); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return getActivity().getLayoutInflater().inflate(R.layout.list_item_schedule_block, parent, false); } @Override public void bindView(View view, Context context, final Cursor cursor) { final String type = cursor.getString(BlocksQuery.BLOCK_TYPE); final String blockId = cursor.getString(BlocksQuery.BLOCK_ID); final String blockTitle = cursor.getString(BlocksQuery.BLOCK_TITLE); final long blockStart = cursor.getLong(BlocksQuery.BLOCK_START); final long blockEnd = cursor.getLong(BlocksQuery.BLOCK_END); final String blockMeta = cursor.getString(BlocksQuery.BLOCK_META); final String blockTimeString = UIUtils.formatBlockTimeString(blockStart, blockEnd, context); final TextView timeView = (TextView) view.findViewById(R.id.block_time); final TextView titleView = (TextView) view.findViewById(R.id.block_title); final TextView subtitleView = (TextView) view.findViewById(R.id.block_subtitle); final ImageButton extraButton = (ImageButton) view.findViewById(R.id.extra_button); final View primaryTouchTargetView = view.findViewById(R.id.list_item_middle_container); final Resources res = getResources(); String subtitle; boolean isLiveStreamed = false; primaryTouchTargetView.setOnLongClickListener(null); UIUtils.setActivatedCompat(primaryTouchTargetView, false); if (ParserUtils.BLOCK_TYPE_SESSION.equals(type) || ParserUtils.BLOCK_TYPE_CODE_LAB.equals(type)) { final int numStarredSessions = cursor.getInt(BlocksQuery.NUM_STARRED_SESSIONS); final String starredSessionId = cursor.getString(BlocksQuery.STARRED_SESSION_ID); View.OnClickListener allSessionsListener = new View.OnClickListener() { @Override public void onClick(View view) { final Uri sessionsUri = ScheduleContract.Blocks.buildSessionsUri(blockId); final Intent intent = new Intent(Intent.ACTION_VIEW, sessionsUri); intent.putExtra(Intent.EXTRA_TITLE, blockTimeString); startActivity(intent); } }; if (numStarredSessions == 0) { // 0 sessions starred titleView.setText(getString(R.string.schedule_empty_slot_title_template, TextUtils.isEmpty(blockTitle) ? "" : (" " + blockTitle.toLowerCase()))); titleView.setTextColor(res.getColorStateList(R.color.body_text_1_positive)); subtitle = getString(R.string.schedule_empty_slot_subtitle); extraButton.setVisibility(View.GONE); primaryTouchTargetView.setOnClickListener(allSessionsListener); } else if (numStarredSessions == 1) { // exactly 1 session starred final String starredSessionTitle = cursor.getString(BlocksQuery.STARRED_SESSION_TITLE); titleView.setText(starredSessionTitle); titleView.setTextColor(res.getColorStateList(R.color.body_text_1)); subtitle = cursor.getString(BlocksQuery.STARRED_SESSION_ROOM_NAME); if (subtitle == null) { // TODO: remove this WAR for API not returning rooms for code labs subtitle = getString( starredSessionTitle.contains("Code Lab") ? R.string.codelab_room : R.string.unknown_room); } isLiveStreamed = !TextUtils.isEmpty( cursor.getString(BlocksQuery.STARRED_SESSION_LIVESTREAM_URL)); extraButton.setVisibility(View.VISIBLE); extraButton.setOnClickListener(allSessionsListener); if (mLongClickedItemData != null && mActionMode != null && mLongClickedItemData.get(BlocksQuery.STARRED_SESSION_ID, "").equals( starredSessionId)) { UIUtils.setActivatedCompat(primaryTouchTargetView, true); mLongClickedView = primaryTouchTargetView; } primaryTouchTargetView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final Uri sessionUri = ScheduleContract.Sessions.buildSessionUri( starredSessionId); final Intent intent = new Intent(Intent.ACTION_VIEW, sessionUri); intent.putExtra(SessionsVendorsMultiPaneActivity.EXTRA_MASTER_URI, ScheduleContract.Blocks.buildSessionsUri(blockId)); intent.putExtra(Intent.EXTRA_TITLE, blockTimeString); startActivity(intent); } }); primaryTouchTargetView.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { if (mActionMode != null) { // CAB already displayed, ignore return true; } mLongClickedView = primaryTouchTargetView; String hashtags = cursor.getString(BlocksQuery.STARRED_SESSION_HASHTAGS); String url = cursor.getString(BlocksQuery.STARRED_SESSION_URL); String roomId = cursor.getString(BlocksQuery.STARRED_SESSION_ROOM_ID); mLongClickedItemData = new SparseArray<String>(); mLongClickedItemData.put(BlocksQuery.STARRED_SESSION_ID, starredSessionId); mLongClickedItemData.put(BlocksQuery.STARRED_SESSION_TITLE, starredSessionTitle); mLongClickedItemData.put(BlocksQuery.STARRED_SESSION_HASHTAGS, hashtags); mLongClickedItemData.put(BlocksQuery.STARRED_SESSION_URL, url); mLongClickedItemData.put(BlocksQuery.STARRED_SESSION_ROOM_ID, roomId); mActionMode = ActionMode.start(getActivity(), MyScheduleFragment.this); UIUtils.setActivatedCompat(primaryTouchTargetView, true); return true; } }); } else { // 2 or more sessions starred titleView.setText(getString(R.string.schedule_conflict_title, numStarredSessions)); titleView.setTextColor(res.getColorStateList(R.color.body_text_1)); subtitle = getString(R.string.schedule_conflict_subtitle); extraButton.setVisibility(View.VISIBLE); extraButton.setOnClickListener(allSessionsListener); primaryTouchTargetView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final Uri sessionsUri = ScheduleContract.Blocks .buildStarredSessionsUri( blockId); final Intent intent = new Intent(Intent.ACTION_VIEW, sessionsUri); intent.putExtra(Intent.EXTRA_TITLE, blockTimeString); startActivity(intent); } }); } subtitleView.setTextColor(res.getColorStateList(R.color.body_text_2)); primaryTouchTargetView.setEnabled(true); } else if (ParserUtils.BLOCK_TYPE_KEYNOTE.equals(type)) { final String starredSessionId = cursor.getString(BlocksQuery.STARRED_SESSION_ID); final String starredSessionTitle = cursor.getString(BlocksQuery.STARRED_SESSION_TITLE); long currentTimeMillis = UIUtils.getCurrentTime(context); boolean past = (currentTimeMillis > blockEnd && currentTimeMillis < UIUtils.CONFERENCE_END_MILLIS); boolean present = !past && (currentTimeMillis >= blockStart); boolean canViewStream = present && UIUtils.hasHoneycomb(); isLiveStreamed = true; titleView.setTextColor(canViewStream ? res.getColorStateList(R.color.body_text_1) : res.getColorStateList(R.color.body_text_disabled)); subtitleView.setTextColor(canViewStream ? res.getColorStateList(R.color.body_text_2) : res.getColorStateList(R.color.body_text_disabled)); subtitle = getString(R.string.keynote_room); titleView.setText(starredSessionTitle); extraButton.setVisibility(View.GONE); primaryTouchTargetView.setEnabled(canViewStream); primaryTouchTargetView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final Uri sessionUri = ScheduleContract.Sessions.buildSessionUri( starredSessionId); Intent livestreamIntent = new Intent(Intent.ACTION_VIEW, sessionUri); livestreamIntent.setClass(getActivity(), SessionLivestreamActivity.class); startActivity(livestreamIntent); } }); } else { titleView.setTextColor(res.getColorStateList(R.color.body_text_disabled)); subtitleView.setTextColor(res.getColorStateList(R.color.body_text_disabled)); subtitle = blockMeta; titleView.setText(blockTitle); extraButton.setVisibility(View.GONE); primaryTouchTargetView.setEnabled(false); primaryTouchTargetView.setOnClickListener(null); } timeView.setText(DateUtils.formatDateTime(context, blockStart, DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_12HOUR)); // Show past/present/future and livestream status for this block. UIUtils.updateTimeAndLivestreamBlockUI(context, blockStart, blockEnd, isLiveStreamed, view, titleView, subtitleView, subtitle); } } private interface BlocksQuery { String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Blocks.BLOCK_ID, ScheduleContract.Blocks.BLOCK_TITLE, ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_END, ScheduleContract.Blocks.BLOCK_TYPE, ScheduleContract.Blocks.BLOCK_META, ScheduleContract.Blocks.SESSIONS_COUNT, ScheduleContract.Blocks.NUM_STARRED_SESSIONS, ScheduleContract.Blocks.STARRED_SESSION_ID, ScheduleContract.Blocks.STARRED_SESSION_TITLE, ScheduleContract.Blocks.STARRED_SESSION_ROOM_NAME, ScheduleContract.Blocks.STARRED_SESSION_ROOM_ID, ScheduleContract.Blocks.STARRED_SESSION_HASHTAGS, ScheduleContract.Blocks.STARRED_SESSION_URL, ScheduleContract.Blocks.STARRED_SESSION_LIVESTREAM_URL, }; int _ID = 0; int BLOCK_ID = 1; int BLOCK_TITLE = 2; int BLOCK_START = 3; int BLOCK_END = 4; int BLOCK_TYPE = 5; int BLOCK_META = 6; int SESSIONS_COUNT = 7; int NUM_STARRED_SESSIONS = 8; int STARRED_SESSION_ID = 9; int STARRED_SESSION_TITLE = 10; int STARRED_SESSION_ROOM_NAME = 11; int STARRED_SESSION_ROOM_ID = 12; int STARRED_SESSION_HASHTAGS = 13; int STARRED_SESSION_URL = 14; int STARRED_SESSION_LIVESTREAM_URL = 15; } }
1162584980-google-io
android/src/com/google/android/apps/iosched/ui/MyScheduleFragment.java
Java
asf20
24,254
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.util.BeamUtils; /** * Beam easter egg landing screen. */ public class BeamActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_beam); } @Override protected void onResume() { super.onResume(); if (BeamUtils.wasLaunchedThroughBeamFirstTime(this, getIntent())) { BeamUtils.setBeamUnlocked(this); showUnlockDialog(); } } void showUnlockDialog() { new AlertDialog.Builder(this) .setTitle(R.string.just_beamed) .setMessage(R.string.beam_unlocked_default) .setNegativeButton(R.string.close, null) .setPositiveButton(R.string.view_beam_session, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { BeamUtils.launchBeamSession(BeamActivity.this); di.dismiss(); } }) .create() .show(); } void showHelpDialog() { new AlertDialog.Builder(this) .setTitle(R.string.title_beam) .setMessage(R.string.beam_unlocked_help) .setNegativeButton(R.string.close, null) .setPositiveButton(R.string.view_beam_session, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { BeamUtils.launchBeamSession(BeamActivity.this); di.dismiss(); } }) .create() .show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getSupportMenuInflater().inflate(R.menu.beam, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.menu_beam_help) { showHelpDialog(); return true; } return super.onOptionsItemSelected(item); } }
1162584980-google-io
android/src/com/google/android/apps/iosched/ui/BeamActivity.java
Java
asf20
3,300
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.AccountUtils; import com.google.api.client.googleapis.extensions.android2.auth.GoogleAccountManager; import com.actionbarsherlock.app.SherlockFragment; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.app.SherlockListFragment; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import android.accounts.Account; import android.accounts.AccountManager; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.os.Handler; import android.provider.Settings; import android.text.Html; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.Arrays; import java.util.List; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * The first activity most users see. This wizard-like activity first presents an account * selection fragment ({@link ChooseAccountFragment}), and then an authentication progress fragment * ({@link AuthProgressFragment}). */ public class AccountActivity extends SherlockFragmentActivity implements AccountUtils.AuthenticateCallback { private static final String TAG = makeLogTag(AccountActivity.class); public static final String EXTRA_FINISH_INTENT = "com.google.android.iosched.extra.FINISH_INTENT"; private static final int REQUEST_AUTHENTICATE = 100; private final Handler mHandler = new Handler(); private Account mChosenAccount; private Intent mFinishIntent; private boolean mCancelAuth = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_account); if (getIntent().hasExtra(EXTRA_FINISH_INTENT)) { mFinishIntent = getIntent().getParcelableExtra(EXTRA_FINISH_INTENT); } if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.fragment_container, new ChooseAccountFragment(), "choose_account") .commit(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_AUTHENTICATE) { if (resultCode == RESULT_OK) { tryAuthenticate(); } else { // go back to previous step mHandler.post(new Runnable() { @Override public void run() { getSupportFragmentManager().popBackStack(); } }); } } else { super.onActivityResult(requestCode, resultCode, data); } } private void tryAuthenticate() { AccountUtils.tryAuthenticate(AccountActivity.this, AccountActivity.this, REQUEST_AUTHENTICATE, mChosenAccount); } @Override public boolean shouldCancelAuthentication() { return mCancelAuth; } @Override public void onAuthTokenAvailable(String authToken) { ContentResolver.setIsSyncable(mChosenAccount, ScheduleContract.CONTENT_AUTHORITY, 1); if (mFinishIntent != null) { mFinishIntent.addCategory(Intent.CATEGORY_LAUNCHER); mFinishIntent.setAction(Intent.ACTION_MAIN); mFinishIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(mFinishIntent); } finish(); } /** * A fragment that presents the user with a list of accounts to choose from. Once an account is * selected, we move on to the login progress fragment ({@link AuthProgressFragment}). */ public static class ChooseAccountFragment extends SherlockListFragment { public ChooseAccountFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public void onResume() { super.onResume(); reloadAccountList(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.add_account, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.menu_add_account) { Intent addAccountIntent = new Intent(Settings.ACTION_ADD_ACCOUNT); addAccountIntent.putExtra(Settings.EXTRA_AUTHORITIES, new String[]{ScheduleContract.CONTENT_AUTHORITY}); startActivity(addAccountIntent); return true; } return super.onOptionsItemSelected(item); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup rootView = (ViewGroup) inflater.inflate( R.layout.fragment_login_choose_account, container, false); TextView descriptionView = (TextView) rootView.findViewById(R.id.choose_account_intro); descriptionView.setText(Html.fromHtml(getString(R.string.description_choose_account))); return rootView; } private AccountListAdapter mAccountListAdapter; private void reloadAccountList() { if (mAccountListAdapter != null) { mAccountListAdapter = null; } AccountManager am = AccountManager.get(getActivity()); Account[] accounts = am.getAccountsByType(GoogleAccountManager.ACCOUNT_TYPE); mAccountListAdapter = new AccountListAdapter(getActivity(), Arrays.asList(accounts)); setListAdapter(mAccountListAdapter); } private class AccountListAdapter extends ArrayAdapter<Account> { private static final int LAYOUT_RESOURCE = android.R.layout.simple_list_item_1; public AccountListAdapter(Context context, List<Account> accounts) { super(context, LAYOUT_RESOURCE, accounts); } private class ViewHolder { TextView text1; } public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = getLayoutInflater(null).inflate(LAYOUT_RESOURCE, null); holder = new ViewHolder(); holder.text1 = (TextView) convertView.findViewById(android.R.id.text1); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } final Account account = getItem(position); if (account != null) { holder.text1.setText(account.name); } else { holder.text1.setText(""); } return convertView; } } @Override public void onListItemClick(ListView l, View v, int position, long id) { AccountActivity activity = (AccountActivity) getActivity(); ConnectivityManager cm = (ConnectivityManager) activity.getSystemService(CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); if (activeNetwork == null || !activeNetwork.isConnected()) { Toast.makeText(activity, R.string.no_connection_cant_login, Toast.LENGTH_SHORT).show(); return; } activity.mCancelAuth = false; activity.mChosenAccount = mAccountListAdapter.getItem(position); activity.getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container, new AuthProgressFragment(), "loading") .addToBackStack("choose_account") .commit(); activity.tryAuthenticate(); } } /** * This fragment shows a login progress spinner. Upon reaching a timeout of 7 seconds (in case * of a poor network connection), the user can try again. */ public static class AuthProgressFragment extends SherlockFragment { private static final int TRY_AGAIN_DELAY_MILLIS = 7 * 1000; // 7 seconds private final Handler mHandler = new Handler(); public AuthProgressFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_login_loading, container, false); final View takingAWhilePanel = rootView.findViewById(R.id.taking_a_while_panel); final View tryAgainButton = rootView.findViewById(R.id.retry_button); tryAgainButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { getFragmentManager().popBackStack(); } }); mHandler.postDelayed(new Runnable() { @Override public void run() { if (!isAdded()) { return; } takingAWhilePanel.setVisibility(View.VISIBLE); } }, TRY_AGAIN_DELAY_MILLIS); return rootView; } @Override public void onDetach() { super.onDetach(); ((AccountActivity) getActivity()).mCancelAuth = true; } } }
1162584980-google-io
android/src/com/google/android/apps/iosched/ui/AccountActivity.java
Java
asf20
11,121
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.BuildConfig; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.util.UIUtils; import com.actionbarsherlock.app.SherlockFragment; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.ConsoleMessage; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Toast; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.LOGE; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * Shows a {@link WebView} with a map of the conference venue. */ public class MapFragment extends SherlockFragment { private static final String TAG = makeLogTag(MapFragment.class); /** * When specified, will automatically point the map to the requested room. */ public static final String EXTRA_ROOM = "com.google.android.iosched.extra.ROOM"; private static final String SYSTEM_FEATURE_MULTITOUCH = "android.hardware.touchscreen.multitouch"; private static final String MAP_JSI_NAME = "MAP_CONTAINER"; private static final String MAP_URL = "http://ioschedmap.appspot.com/embed.html"; private static boolean CLEAR_CACHE_ON_LOAD = BuildConfig.DEBUG; private WebView mWebView; private View mLoadingSpinner; private boolean mMapInitialized = false; public interface Callbacks { public void onRoomSelected(String roomId); } private static Callbacks sDummyCallbacks = new Callbacks() { @Override public void onRoomSelected(String roomId) { } }; private Callbacks mCallbacks = sDummyCallbacks; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); EasyTracker.getTracker().trackView("Map"); LOGD("Tracker", "Map"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_webview_with_spinner, container, false); mLoadingSpinner = root.findViewById(R.id.loading_spinner); mWebView = (WebView) root.findViewById(R.id.webview); mWebView.setWebChromeClient(mWebChromeClient); mWebView.setWebViewClient(mWebViewClient); return root; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // Initialize web view if (CLEAR_CACHE_ON_LOAD) { mWebView.clearCache(true); } boolean hideZoomControls = getActivity().getPackageManager().hasSystemFeature(SYSTEM_FEATURE_MULTITOUCH) && UIUtils.hasHoneycomb(); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(false); mWebView.loadUrl(MAP_URL + "?multitouch=" + (hideZoomControls ? 1 : 0)); mWebView.addJavascriptInterface(mMapJsiImpl, MAP_JSI_NAME); } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (!(activity instanceof Callbacks)) { throw new ClassCastException("Activity must implement fragment's callbacks."); } mCallbacks = (Callbacks) activity; } @Override public void onDetach() { super.onDetach(); mCallbacks = sDummyCallbacks; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.map, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.menu_refresh) { mWebView.reload(); return true; } return super.onOptionsItemSelected(item); } private void runJs(final String js) { Activity activity = getActivity(); if (activity == null) { return; } activity.runOnUiThread(new Runnable() { @Override public void run() { LOGD(TAG, "Loading javascript:" + js); mWebView.loadUrl("javascript:" + js); } }); } /** * Helper method to escape JavaScript strings. Useful when passing strings to a WebView via * "javascript:" calls. */ private static String escapeJsString(String s) { if (s == null) { return ""; } return s.replace("'", "\\'").replace("\"", "\\\""); } public void panBy(float xFraction, float yFraction) { runJs("IoMap.panBy(" + xFraction + "," + yFraction + ");"); } /** * I/O Conference Map JavaScript interface. */ private interface MapJsi { public void openContentInfo(final String roomId); public void onMapReady(); } private final WebChromeClient mWebChromeClient = new WebChromeClient() { @Override public boolean onConsoleMessage(ConsoleMessage consoleMessage) { LOGD(TAG, "JS Console message: (" + consoleMessage.sourceId() + ": " + consoleMessage.lineNumber() + ") " + consoleMessage.message()); return false; } }; private final WebViewClient mWebViewClient = new WebViewClient() { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); mLoadingSpinner.setVisibility(View.VISIBLE); mWebView.setVisibility(View.INVISIBLE); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); mLoadingSpinner.setVisibility(View.GONE); mWebView.setVisibility(View.VISIBLE); } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { LOGE(TAG, "Error " + errorCode + ": " + description); Toast.makeText(view.getContext(), "Error " + errorCode + ": " + description, Toast.LENGTH_LONG).show(); super.onReceivedError(view, errorCode, description, failingUrl); } }; private final MapJsi mMapJsiImpl = new MapJsi() { public void openContentInfo(final String roomId) { Activity activity = getActivity(); if (activity == null) { return; } activity.runOnUiThread(new Runnable() { @Override public void run() { mCallbacks.onRoomSelected(roomId); } }); } public void onMapReady() { LOGD(TAG, "onMapReady"); final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments()); String showRoomId = null; if (!mMapInitialized && intent.hasExtra(EXTRA_ROOM)) { showRoomId = intent.getStringExtra(EXTRA_ROOM); } if (showRoomId != null) { runJs("IoMap.showLocationById('" + escapeJsString(showRoomId) + "');"); } mMapInitialized = true; } }; }
1162584980-google-io
android/src/com/google/android/apps/iosched/ui/MapFragment.java
Java
asf20
8,494
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; /** * A {@link BaseActivity} that simply contains a single fragment. The intent used to invoke this * activity is forwarded to the fragment as arguments during fragment instantiation. Derived * activities should only need to implement {@link SimpleSinglePaneActivity#onCreatePane()}. */ public abstract class SimpleSinglePaneActivity extends BaseActivity { private Fragment mFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_singlepane_empty); if (getIntent().hasExtra(Intent.EXTRA_TITLE)) { setTitle(getIntent().getStringExtra(Intent.EXTRA_TITLE)); } final String customTitle = getIntent().getStringExtra(Intent.EXTRA_TITLE); setTitle(customTitle != null ? customTitle : getTitle()); if (savedInstanceState == null) { mFragment = onCreatePane(); mFragment.setArguments(intentToFragmentArguments(getIntent())); getSupportFragmentManager().beginTransaction() .add(R.id.root_container, mFragment, "single_pane") .commit(); } else { mFragment = getSupportFragmentManager().findFragmentByTag("single_pane"); } } /** * Called in <code>onCreate</code> when the fragment constituting this activity is needed. * The returned fragment's arguments will be set to the intent used to invoke this activity. */ protected abstract Fragment onCreatePane(); public Fragment getFragment() { return mFragment; } }
1162584980-google-io
android/src/com/google/android/apps/iosched/ui/SimpleSinglePaneActivity.java
Java
asf20
2,407
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.TracksAdapter.TracksQuery; import com.google.android.apps.iosched.util.UIUtils; import com.actionbarsherlock.app.SherlockListFragment; import android.app.Activity; import android.content.Intent; import android.database.ContentObserver; import android.database.Cursor; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; /** * A simple {@link ListFragment} that renders a list of tracks and a map button at the top. */ public class ExploreFragment extends SherlockListFragment implements LoaderManager.LoaderCallbacks<Cursor> { private TracksAdapter mAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mAdapter = new TracksAdapter(getActivity()); setListAdapter(mAdapter); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); final ListView listView = getListView(); listView.setSelector(android.R.color.transparent); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // As of support library r8, calling initLoader for a fragment in a // FragmentPagerAdapter in the fragment's onCreate may cause the same LoaderManager to be // dealt to multiple fragments because their mIndex is -1 (haven't been added to the // activity yet). Thus, we do this in onActivityCreated. getLoaderManager().initLoader(TracksQuery._TOKEN, null, this); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup root = (ViewGroup) inflater.inflate( R.layout.fragment_list_with_empty_container, container, false); root.setBackgroundColor(Color.WHITE); return root; } private final ContentObserver mObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { if (getActivity() == null) { return; } Loader<Cursor> loader = getLoaderManager().getLoader(TracksQuery._TOKEN); if (loader != null) { loader.forceLoad(); } } }; @Override public void onAttach(Activity activity) { super.onAttach(activity); activity.getContentResolver().registerContentObserver( ScheduleContract.Sessions.CONTENT_URI, true, mObserver); } @Override public void onDetach() { super.onDetach(); getActivity().getContentResolver().unregisterContentObserver(mObserver); } /** {@inheritDoc} */ @Override public void onListItemClick(ListView l, View v, int position, long id) { if (mAdapter.isMapItem(position)) { // Launch map of conference venue EasyTracker.getTracker().trackEvent( "Home Screen Dashboard", "Click", "Map", 0L); startActivity(new Intent(getActivity(), UIUtils.getMapActivityClass(getActivity()))); return; } final Cursor cursor = (Cursor) mAdapter.getItem(position); final String trackId; if (cursor != null) { trackId = cursor.getString(TracksAdapter.TracksQuery.TRACK_ID); } else { trackId = ScheduleContract.Tracks.ALL_TRACK_ID; } final Intent intent = new Intent(Intent.ACTION_VIEW); final Uri trackUri = ScheduleContract.Tracks.buildTrackUri(trackId); intent.setData(trackUri); startActivity(intent); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments()); Uri tracksUri = intent.getData(); if (tracksUri == null) { tracksUri = ScheduleContract.Tracks.CONTENT_URI; } // Filter our tracks query to only include those with valid results String[] projection = TracksAdapter.TracksQuery.PROJECTION; String selection = null; return new CursorLoader(getActivity(), tracksUri, projection, selection, null, ScheduleContract.Tracks.DEFAULT_SORT); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if (getActivity() == null) { return; } mAdapter.setHasMapItem(true); mAdapter.setHasAllItem(true); mAdapter.changeCursor(cursor); } @Override public void onLoaderReset(Loader<Cursor> loader) { } }
1162584980-google-io
android/src/com/google/android/apps/iosched/ui/ExploreFragment.java
Java
asf20
5,900
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.Config; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.calendar.SessionAlarmService; import com.google.android.apps.iosched.calendar.SessionCalendarService; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.FractionalTouchDelegate; import com.google.android.apps.iosched.util.HelpUtils; import com.google.android.apps.iosched.util.ImageFetcher; import com.google.android.apps.iosched.util.SessionsHelper; import com.google.android.apps.iosched.util.UIUtils; import com.google.api.android.plus.GooglePlus; import com.google.api.android.plus.PlusOneButton; import com.actionbarsherlock.app.SherlockFragment; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.RectF; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * A fragment that shows detail information for a session, including session title, abstract, * time information, speaker photos and bios, etc. * * <p>This fragment is used in a number of activities, including * {@link com.google.android.apps.iosched.ui.phone.SessionDetailActivity}, * {@link com.google.android.apps.iosched.ui.tablet.SessionsVendorsMultiPaneActivity}, * {@link com.google.android.apps.iosched.ui.tablet.MapMultiPaneActivity}, etc. */ public class SessionDetailFragment extends SherlockFragment implements LoaderManager.LoaderCallbacks<Cursor> { private static final String TAG = makeLogTag(SessionDetailFragment.class); // Set this boolean extra to true to show a variable height header public static final String EXTRA_VARIABLE_HEIGHT_HEADER = "com.google.android.iosched.extra.VARIABLE_HEIGHT_HEADER"; private String mSessionId; private Uri mSessionUri; private long mSessionBlockStart; private long mSessionBlockEnd; private String mTitleString; private String mHashtags; private String mUrl; private String mRoomId; private String mRoomName; private boolean mStarred; private boolean mInitStarred; private MenuItem mShareMenuItem; private MenuItem mStarMenuItem; private MenuItem mSocialStreamMenuItem; private ViewGroup mRootView; private TextView mTitle; private TextView mSubtitle; private PlusOneButton mPlusOneButton; private TextView mAbstract; private TextView mRequirements; private boolean mSessionCursor = false; private boolean mSpeakersCursor = false; private boolean mHasSummaryContent = false; private boolean mVariableHeightHeader = false; private ImageFetcher mImageFetcher; private List<Runnable> mDeferredUiOperations = new ArrayList<Runnable>(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); GooglePlus.initialize(getActivity(), Config.API_KEY, Config.CLIENT_ID); final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments()); mSessionUri = intent.getData(); if (mSessionUri == null) { return; } mSessionId = ScheduleContract.Sessions.getSessionId(mSessionUri); mVariableHeightHeader = intent.getBooleanExtra(EXTRA_VARIABLE_HEIGHT_HEADER, false); LoaderManager manager = getLoaderManager(); manager.restartLoader(SessionsQuery._TOKEN, null, this); manager.restartLoader(SpeakersQuery._TOKEN, null, this); mImageFetcher = UIUtils.getImageFetcher(getActivity()); mImageFetcher.setImageFadeIn(false); setHasOptionsMenu(true); HelpUtils.maybeShowAddToScheduleTutorial(getActivity()); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = (ViewGroup) inflater.inflate(R.layout.fragment_session_detail, null); mTitle = (TextView) mRootView.findViewById(R.id.session_title); mSubtitle = (TextView) mRootView.findViewById(R.id.session_subtitle); // Larger target triggers plus one button mPlusOneButton = (PlusOneButton) mRootView.findViewById(R.id.plus_one_button); final View plusOneParent = mRootView.findViewById(R.id.header_session); FractionalTouchDelegate.setupDelegate(plusOneParent, mPlusOneButton, new RectF(0.6f, 0f, 1f, 1.0f)); mAbstract = (TextView) mRootView.findViewById(R.id.session_abstract); mRequirements = (TextView) mRootView.findViewById(R.id.session_requirements); if (mVariableHeightHeader) { View headerView = mRootView.findViewById(R.id.header_session); ViewGroup.LayoutParams layoutParams = headerView.getLayoutParams(); layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT; headerView.setLayoutParams(layoutParams); } return mRootView; } @Override public void onStop() { super.onStop(); if (mInitStarred != mStarred) { // Update Calendar event through the Calendar API on Android 4.0 or new versions. if (UIUtils.hasICS()) { Intent intent; if (mStarred) { // Set up intent to add session to Calendar, if it doesn't exist already. intent = new Intent(SessionCalendarService.ACTION_ADD_SESSION_CALENDAR, mSessionUri); intent.putExtra(SessionCalendarService.EXTRA_SESSION_BLOCK_START, mSessionBlockStart); intent.putExtra(SessionCalendarService.EXTRA_SESSION_BLOCK_END, mSessionBlockEnd); intent.putExtra(SessionCalendarService.EXTRA_SESSION_ROOM, mRoomName); intent.putExtra(SessionCalendarService.EXTRA_SESSION_TITLE, mTitleString); } else { // Set up intent to remove session from Calendar, if exists. intent = new Intent(SessionCalendarService.ACTION_REMOVE_SESSION_CALENDAR, mSessionUri); intent.putExtra(SessionCalendarService.EXTRA_SESSION_BLOCK_START, mSessionBlockStart); intent.putExtra(SessionCalendarService.EXTRA_SESSION_BLOCK_END, mSessionBlockEnd); intent.putExtra(SessionCalendarService.EXTRA_SESSION_TITLE, mTitleString); } intent.setClass(getActivity(), SessionCalendarService.class); getActivity().startService(intent); } if (mStarred && System.currentTimeMillis() < mSessionBlockStart) { setupNotification(); } } } @Override public void onPause() { super.onPause(); mImageFetcher.flushCache(); } @Override public void onDestroy() { super.onDestroy(); mImageFetcher.closeCache(); } private void setupNotification() { // Schedule an alarm that fires a system notification when expires. final Context ctx = getActivity(); Intent scheduleIntent = new Intent( SessionAlarmService.ACTION_SCHEDULE_STARRED_BLOCK, null, ctx, SessionAlarmService.class); scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_START, mSessionBlockStart); scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_END, mSessionBlockEnd); ctx.startService(scheduleIntent); } /** * Handle {@link SessionsQuery} {@link Cursor}. */ private void onSessionQueryComplete(Cursor cursor) { mSessionCursor = true; if (!cursor.moveToFirst()) { return; } mTitleString = cursor.getString(SessionsQuery.TITLE); // Format time block this session occupies mSessionBlockStart = cursor.getLong(SessionsQuery.BLOCK_START); mSessionBlockEnd = cursor.getLong(SessionsQuery.BLOCK_END); mRoomName = cursor.getString(SessionsQuery.ROOM_NAME); final String subtitle = UIUtils.formatSessionSubtitle( mTitleString, mSessionBlockStart, mSessionBlockEnd, mRoomName, getActivity()); mTitle.setText(mTitleString); mUrl = cursor.getString(SessionsQuery.URL); if (TextUtils.isEmpty(mUrl)) { mUrl = ""; } mHashtags = cursor.getString(SessionsQuery.HASHTAGS); if (!TextUtils.isEmpty(mHashtags)) { enableSocialStreamMenuItemDeferred(); } mRoomId = cursor.getString(SessionsQuery.ROOM_ID); setupShareMenuItemDeferred(); showStarredDeferred(mInitStarred = (cursor.getInt(SessionsQuery.STARRED) != 0)); final String sessionAbstract = cursor.getString(SessionsQuery.ABSTRACT); if (!TextUtils.isEmpty(sessionAbstract)) { UIUtils.setTextMaybeHtml(mAbstract, sessionAbstract); mAbstract.setVisibility(View.VISIBLE); mHasSummaryContent = true; } else { mAbstract.setVisibility(View.GONE); } mPlusOneButton.setSize(PlusOneButton.Size.TALL); String url = cursor.getString(SessionsQuery.URL); if (TextUtils.isEmpty(url)) { mPlusOneButton.setVisibility(View.GONE); } else { mPlusOneButton.setUrl(url); } final View requirementsBlock = mRootView.findViewById(R.id.session_requirements_block); final String sessionRequirements = cursor.getString(SessionsQuery.REQUIREMENTS); if (!TextUtils.isEmpty(sessionRequirements)) { UIUtils.setTextMaybeHtml(mRequirements, sessionRequirements); requirementsBlock.setVisibility(View.VISIBLE); mHasSummaryContent = true; } else { requirementsBlock.setVisibility(View.GONE); } // Show empty message when all data is loaded, and nothing to show if (mSpeakersCursor && !mHasSummaryContent) { mRootView.findViewById(android.R.id.empty).setVisibility(View.VISIBLE); } ViewGroup linksContainer = (ViewGroup) mRootView.findViewById(R.id.links_container); linksContainer.removeAllViews(); LayoutInflater inflater = getLayoutInflater(null); boolean hasLinks = false; final Context context = mRootView.getContext(); // Render I/O live link final boolean hasLivestream = !TextUtils.isEmpty( cursor.getString(SessionsQuery.LIVESTREAM_URL)); long currentTimeMillis = UIUtils.getCurrentTime(context); if (UIUtils.hasHoneycomb() // Needs Honeycomb+ for the live stream && hasLivestream && currentTimeMillis > mSessionBlockStart && currentTimeMillis <= mSessionBlockEnd) { hasLinks = true; // Create the link item ViewGroup linkContainer = (ViewGroup) inflater.inflate(R.layout.list_item_session_link, linksContainer, false); ((TextView) linkContainer.findViewById(R.id.link_text)).setText( R.string.session_link_livestream); linkContainer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { fireLinkEvent(R.string.session_link_livestream); Intent livestreamIntent = new Intent(Intent.ACTION_VIEW, mSessionUri); livestreamIntent.setClass(context, SessionLivestreamActivity.class); startActivity(livestreamIntent); } }); linksContainer.addView(linkContainer); } // Render normal links for (int i = 0; i < SessionsQuery.LINKS_INDICES.length; i++) { final String linkUrl = cursor.getString(SessionsQuery.LINKS_INDICES[i]); if (!TextUtils.isEmpty(linkUrl)) { hasLinks = true; // Create the link item ViewGroup linkContainer = (ViewGroup) inflater.inflate(R.layout.list_item_session_link, linksContainer, false); ((TextView) linkContainer.findViewById(R.id.link_text)).setText( SessionsQuery.LINKS_TITLES[i]); final int linkTitleIndex = i; linkContainer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { fireLinkEvent(SessionsQuery.LINKS_TITLES[linkTitleIndex]); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(linkUrl)); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); UIUtils.safeOpenLink(context, intent); } }); linksContainer.addView(linkContainer); } } // Show past/present/future and livestream status for this block. UIUtils.updateTimeAndLivestreamBlockUI(context, mSessionBlockStart, mSessionBlockEnd, hasLivestream, null, null, mSubtitle, subtitle); mRootView.findViewById(R.id.session_links_block) .setVisibility(hasLinks ? View.VISIBLE : View.GONE); EasyTracker.getTracker().trackView("Session: " + mTitleString); LOGD("Tracker", "Session: " + mTitleString); } private void enableSocialStreamMenuItemDeferred() { mDeferredUiOperations.add(new Runnable() { @Override public void run() { mSocialStreamMenuItem.setVisible(true); } }); tryExecuteDeferredUiOperations(); } private void showStarredDeferred(final boolean starred) { mDeferredUiOperations.add(new Runnable() { @Override public void run() { showStarred(starred); } }); tryExecuteDeferredUiOperations(); } private void showStarred(boolean starred) { mStarMenuItem.setTitle(starred ? R.string.description_remove_schedule : R.string.description_add_schedule); mStarMenuItem.setIcon(starred ? R.drawable.ic_action_remove_schedule : R.drawable.ic_action_add_schedule); mStarred = starred; } private void setupShareMenuItemDeferred() { mDeferredUiOperations.add(new Runnable() { @Override public void run() { new SessionsHelper(getActivity()) .tryConfigureShareMenuItem(mShareMenuItem, R.string.share_template, mTitleString, mHashtags, mUrl); } }); tryExecuteDeferredUiOperations(); } private void tryExecuteDeferredUiOperations() { if (mStarMenuItem != null && mSocialStreamMenuItem != null) { for (Runnable r : mDeferredUiOperations) { r.run(); } mDeferredUiOperations.clear(); } } private void onSpeakersQueryComplete(Cursor cursor) { mSpeakersCursor = true; // TODO: remove existing speakers from layout, since this cursor might be from a data change final ViewGroup speakersGroup = (ViewGroup) mRootView.findViewById(R.id.session_speakers_block); final LayoutInflater inflater = getActivity().getLayoutInflater(); boolean hasSpeakers = false; while (cursor.moveToNext()) { final String speakerName = cursor.getString(SpeakersQuery.SPEAKER_NAME); if (TextUtils.isEmpty(speakerName)) { continue; } final String speakerImageUrl = cursor.getString(SpeakersQuery.SPEAKER_IMAGE_URL); final String speakerCompany = cursor.getString(SpeakersQuery.SPEAKER_COMPANY); final String speakerUrl = cursor.getString(SpeakersQuery.SPEAKER_URL); final String speakerAbstract = cursor.getString(SpeakersQuery.SPEAKER_ABSTRACT); String speakerHeader = speakerName; if (!TextUtils.isEmpty(speakerCompany)) { speakerHeader += ", " + speakerCompany; } final View speakerView = inflater .inflate(R.layout.speaker_detail, speakersGroup, false); final TextView speakerHeaderView = (TextView) speakerView .findViewById(R.id.speaker_header); final ImageView speakerImageView = (ImageView) speakerView .findViewById(R.id.speaker_image); final TextView speakerAbstractView = (TextView) speakerView .findViewById(R.id.speaker_abstract); if (!TextUtils.isEmpty(speakerImageUrl)) { mImageFetcher.loadThumbnailImage(speakerImageUrl, speakerImageView, R.drawable.person_image_empty); } speakerHeaderView.setText(speakerHeader); speakerImageView.setContentDescription( getString(R.string.speaker_googleplus_profile, speakerHeader)); UIUtils.setTextMaybeHtml(speakerAbstractView, speakerAbstract); if (!TextUtils.isEmpty(speakerUrl)) { speakerImageView.setEnabled(true); speakerImageView.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Intent speakerProfileIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(speakerUrl)); speakerProfileIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); UIUtils.preferPackageForIntent(getActivity(), speakerProfileIntent, UIUtils.GOOGLE_PLUS_PACKAGE_NAME); UIUtils.safeOpenLink(getActivity(), speakerProfileIntent); } }); } else { speakerImageView.setEnabled(false); speakerImageView.setOnClickListener(null); } speakersGroup.addView(speakerView); hasSpeakers = true; mHasSummaryContent = true; } speakersGroup.setVisibility(hasSpeakers ? View.VISIBLE : View.GONE); // Show empty message when all data is loaded, and nothing to show if (mSessionCursor && !mHasSummaryContent) { mRootView.findViewById(android.R.id.empty).setVisibility(View.VISIBLE); } } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.session_detail, menu); mStarMenuItem = menu.findItem(R.id.menu_star); mSocialStreamMenuItem = menu.findItem(R.id.menu_social_stream); mShareMenuItem = menu.findItem(R.id.menu_share); tryExecuteDeferredUiOperations(); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { SessionsHelper helper = new SessionsHelper(getActivity()); switch (item.getItemId()) { case R.id.menu_map: EasyTracker.getTracker().trackEvent( "Session", "Map", mTitleString, 0L); LOGD("Tracker", "Map: " + mTitleString); helper.startMapActivity(mRoomId); return true; case R.id.menu_star: boolean star = !mStarred; showStarred(star); helper.setSessionStarred(mSessionUri, star, mTitleString); Toast.makeText( getActivity(), getResources().getQuantityString(star ? R.plurals.toast_added_to_schedule : R.plurals.toast_removed_from_schedule, 1, 1), Toast.LENGTH_SHORT).show(); EasyTracker.getTracker().trackEvent( "Session", star ? "Starred" : "Unstarred", mTitleString, 0L); LOGD("Tracker", (star ? "Starred: " : "Unstarred: ") + mTitleString); return true; case R.id.menu_share: // On ICS+ devices, we normally won't reach this as ShareActionProvider will handle // sharing. helper.shareSession(getActivity(), R.string.share_template, mTitleString, mHashtags, mUrl); return true; case R.id.menu_social_stream: EasyTracker.getTracker().trackEvent( "Session", "Stream", mTitleString, 0L); LOGD("Tracker", "Stream: " + mTitleString); helper.startSocialStream(UIUtils.getSessionHashtagsString(mHashtags)); return true; } return super.onOptionsItemSelected(item); } /* * Event structure: * Category -> "Session Details" * Action -> Link Text * Label -> Session's Title * Value -> 0. */ public void fireLinkEvent(int actionId) { EasyTracker.getTracker().trackEvent( "Session", getActivity().getString(actionId), mTitleString, 0L); LOGD("Tracker", getActivity().getString(actionId) + ": " + mTitleString); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { CursorLoader loader = null; if (id == SessionsQuery._TOKEN){ loader = new CursorLoader(getActivity(), mSessionUri, SessionsQuery.PROJECTION, null, null, null); } else if (id == SpeakersQuery._TOKEN && mSessionUri != null){ Uri speakersUri = ScheduleContract.Sessions.buildSpeakersDirUri(mSessionId); loader = new CursorLoader(getActivity(), speakersUri, SpeakersQuery.PROJECTION, null, null, null); } return loader; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if (getActivity() == null) { return; } if (loader.getId() == SessionsQuery._TOKEN) { onSessionQueryComplete(cursor); } else if (loader.getId() == SpeakersQuery._TOKEN) { onSpeakersQueryComplete(cursor); } else { cursor.close(); } } @Override public void onLoaderReset(Loader<Cursor> loader) {} /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Sessions} query parameters. */ private interface SessionsQuery { int _TOKEN = 0x1; String[] PROJECTION = { ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_END, ScheduleContract.Sessions.SESSION_LEVEL, ScheduleContract.Sessions.SESSION_TITLE, ScheduleContract.Sessions.SESSION_ABSTRACT, ScheduleContract.Sessions.SESSION_REQUIREMENTS, ScheduleContract.Sessions.SESSION_STARRED, ScheduleContract.Sessions.SESSION_HASHTAGS, ScheduleContract.Sessions.SESSION_URL, ScheduleContract.Sessions.SESSION_YOUTUBE_URL, ScheduleContract.Sessions.SESSION_PDF_URL, ScheduleContract.Sessions.SESSION_NOTES_URL, ScheduleContract.Sessions.SESSION_LIVESTREAM_URL, ScheduleContract.Sessions.ROOM_ID, ScheduleContract.Rooms.ROOM_NAME, }; int BLOCK_START = 0; int BLOCK_END = 1; int LEVEL = 2; int TITLE = 3; int ABSTRACT = 4; int REQUIREMENTS = 5; int STARRED = 6; int HASHTAGS = 7; int URL = 8; int YOUTUBE_URL = 9; int PDF_URL = 10; int NOTES_URL = 11; int LIVESTREAM_URL = 12; int ROOM_ID = 13; int ROOM_NAME = 14; int[] LINKS_INDICES = { URL, YOUTUBE_URL, PDF_URL, NOTES_URL, }; int[] LINKS_TITLES = { R.string.session_link_main, R.string.session_link_youtube, R.string.session_link_pdf, R.string.session_link_notes, }; } private interface SpeakersQuery { int _TOKEN = 0x3; String[] PROJECTION = { ScheduleContract.Speakers.SPEAKER_NAME, ScheduleContract.Speakers.SPEAKER_IMAGE_URL, ScheduleContract.Speakers.SPEAKER_COMPANY, ScheduleContract.Speakers.SPEAKER_ABSTRACT, ScheduleContract.Speakers.SPEAKER_URL, }; int SPEAKER_NAME = 0; int SPEAKER_IMAGE_URL = 1; int SPEAKER_COMPANY = 2; int SPEAKER_ABSTRACT = 3; int SPEAKER_URL = 4; } }
1162584980-google-io
android/src/com/google/android/apps/iosched/ui/SessionDetailFragment.java
Java
asf20
26,488
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract.Announcements; import com.google.android.apps.iosched.util.UIUtils; import android.content.Intent; import android.database.ContentObserver; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.text.TextUtils; import android.text.format.DateUtils; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; /** * A fragment used in {@link HomeActivity} that shows either a countdown, * announcements, or 'thank you' text, at different times (before/during/after * the conference). */ public class WhatsOnFragment extends Fragment implements LoaderCallbacks<Cursor> { private Handler mHandler = new Handler(); private TextView mCountdownTextView; private ViewGroup mRootView; private Cursor mAnnouncementsCursor; private LayoutInflater mInflater; private int mTitleCol = -1; private int mDateCol = -1; private int mUrlCol = -1; private static final int ANNOUNCEMENTS_LOADER_ID = 0; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mInflater = inflater; mRootView = (ViewGroup) inflater.inflate(R.layout.fragment_whats_on, container); refresh(); return mRootView; } @Override public void onDetach() { super.onDetach(); mHandler.removeCallbacks(mCountdownRunnable); getActivity().getContentResolver().unregisterContentObserver(mObserver); } private void refresh() { mHandler.removeCallbacks(mCountdownRunnable); mRootView.removeAllViews(); final long currentTimeMillis = UIUtils.getCurrentTime(getActivity()); // Show Loading... and load the view corresponding to the current state if (currentTimeMillis < UIUtils.CONFERENCE_START_MILLIS) { setupBefore(); } else if (currentTimeMillis > UIUtils.CONFERENCE_END_MILLIS) { setupAfter(); } else { setupDuring(); } } private void setupBefore() { // Before conference, show countdown. mCountdownTextView = (TextView) mInflater .inflate(R.layout.whats_on_countdown, mRootView, false); mRootView.addView(mCountdownTextView); mHandler.post(mCountdownRunnable); } private void setupAfter() { // After conference, show canned text. mInflater.inflate(R.layout.whats_on_thank_you, mRootView, true); } private void setupDuring() { // Start background query to load announcements getLoaderManager().initLoader(ANNOUNCEMENTS_LOADER_ID, null, this); getActivity().getContentResolver().registerContentObserver( Announcements.CONTENT_URI, true, mObserver); } /** * Event that updates countdown timer. Posts itself again to * {@link #mHandler} to continue updating time. */ private final Runnable mCountdownRunnable = new Runnable() { public void run() { int remainingSec = (int) Math.max(0, (UIUtils.CONFERENCE_START_MILLIS - UIUtils .getCurrentTime(getActivity())) / 1000); final boolean conferenceStarted = remainingSec == 0; if (conferenceStarted) { // Conference started while in countdown mode, switch modes and // bail on future countdown updates. mHandler.postDelayed(new Runnable() { public void run() { refresh(); } }, 100); return; } final int secs = remainingSec % 86400; final int days = remainingSec / 86400; final String str; if (days == 0) { str = getResources().getString( R.string.whats_on_countdown_title_0, DateUtils.formatElapsedTime(secs)); } else { str = getResources().getQuantityString( R.plurals.whats_on_countdown_title, days, days, DateUtils.formatElapsedTime(secs)); } mCountdownTextView.setText(str); // Repost ourselves to keep updating countdown mHandler.postDelayed(mCountdownRunnable, 1000); } }; @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { return new CursorLoader(getActivity(), Announcements.CONTENT_URI, null, null, null, Announcements.ANNOUNCEMENT_DATE + " DESC"); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (getActivity() == null) { return; } if (data != null && data.getCount() > 0) { mTitleCol = data.getColumnIndex(Announcements.ANNOUNCEMENT_TITLE); mDateCol = data.getColumnIndex(Announcements.ANNOUNCEMENT_DATE); mUrlCol = data.getColumnIndex(Announcements.ANNOUNCEMENT_URL); showAnnouncements(data); } else { showNoAnnouncements(); } } @Override public void onLoaderReset(Loader<Cursor> loader) { mAnnouncementsCursor = null; } /** * Show the the announcements */ private void showAnnouncements(Cursor announcements) { mAnnouncementsCursor = announcements; ViewGroup announcementsRootView = (ViewGroup) mInflater.inflate( R.layout.whats_on_announcements, mRootView, false); final ViewPager pager = (ViewPager) announcementsRootView.findViewById( R.id.announcements_pager); final View previousButton = announcementsRootView.findViewById( R.id.announcements_previous_button); final View nextButton = announcementsRootView.findViewById( R.id.announcements_next_button); final PagerAdapter adapter = new AnnouncementsAdapter(); pager.setAdapter(adapter); pager.setPageMargin( getResources().getDimensionPixelSize(R.dimen.announcements_margin_width)); pager.setPageMarginDrawable(R.drawable.announcements_divider); pager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { previousButton.setEnabled(position > 0); nextButton.setEnabled(position < adapter.getCount() - 1); } }); previousButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { pager.setCurrentItem(pager.getCurrentItem() - 1); } }); nextButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { pager.setCurrentItem(pager.getCurrentItem() + 1); } }); previousButton.setEnabled(false); nextButton.setEnabled(adapter.getCount() > 1); mRootView.removeAllViews(); mRootView.addView(announcementsRootView); } /** * Show a placeholder message */ private void showNoAnnouncements() { mInflater.inflate(R.layout.empty_announcements, mRootView, true); } public class AnnouncementsAdapter extends PagerAdapter { @Override public Object instantiateItem(ViewGroup pager, int position) { mAnnouncementsCursor.moveToPosition(position); LinearLayout rootView = (LinearLayout) mInflater.inflate( R.layout.pager_item_announcement, pager, false); TextView titleView = (TextView) rootView.findViewById(R.id.announcement_title); TextView subtitleView = (TextView) rootView.findViewById(R.id.announcement_ago); titleView.setText(mAnnouncementsCursor.getString(mTitleCol)); final long date = mAnnouncementsCursor.getLong(mDateCol); final String when = UIUtils.getTimeAgo(date, getActivity()); final String url = mAnnouncementsCursor.getString(mUrlCol); subtitleView.setText(when); rootView.setTag(url); if (!TextUtils.isEmpty(url)) { rootView.setClickable(true); rootView.setOnClickListener(mAnnouncementClick); } else { rootView.setClickable(false); } pager.addView(rootView, 0); return rootView; } private final OnClickListener mAnnouncementClick = new OnClickListener() { @Override public void onClick(View v) { String url = (String) v.getTag(); if (!TextUtils.isEmpty(url)) { UIUtils.safeOpenLink(getActivity(), new Intent(Intent.ACTION_VIEW, Uri.parse(url))); } } }; @Override public void destroyItem(ViewGroup pager, int position, Object view) { pager.removeView((View) view); } @Override public int getCount() { return mAnnouncementsCursor.getCount(); } @Override public boolean isViewFromObject(View view, Object object) { return view.equals(object); } @Override public int getItemPosition(Object object) { return POSITION_NONE; } } private final ContentObserver mObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { if (getActivity() == null) { return; } Loader<Cursor> loader = getLoaderManager().getLoader(ANNOUNCEMENTS_LOADER_ID); if (loader != null) { loader.forceLoad(); } } }; }
1162584980-google-io
android/src/com/google/android/apps/iosched/ui/WhatsOnFragment.java
Java
asf20
11,175
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.ImageFetcher; import com.google.android.apps.iosched.util.UIUtils; import com.actionbarsherlock.app.SherlockFragment; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * A fragment that shows detail information for a developer sandbox company, including * company name, description, logo, etc. */ public class VendorDetailFragment extends SherlockFragment implements LoaderManager.LoaderCallbacks<Cursor> { private static final String TAG = makeLogTag(VendorDetailFragment.class); private Uri mVendorUri; private TextView mName; private ImageView mLogo; private TextView mUrl; private TextView mDesc; private ImageFetcher mImageFetcher; public interface Callbacks { public void onTrackIdAvailable(String trackId); } private static Callbacks sDummyCallbacks = new Callbacks() { @Override public void onTrackIdAvailable(String trackId) {} }; private Callbacks mCallbacks = sDummyCallbacks; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments()); mVendorUri = intent.getData(); if (mVendorUri == null) { return; } mImageFetcher = UIUtils.getImageFetcher(getActivity()); mImageFetcher.setImageFadeIn(false); setHasOptionsMenu(true); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (mVendorUri == null) { return; } // Start background query to load vendor details getLoaderManager().initLoader(VendorsQuery._TOKEN, null, this); } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (!(activity instanceof Callbacks)) { throw new ClassCastException("Activity must implement fragment's callbacks."); } mCallbacks = (Callbacks) activity; } @Override public void onDetach() { super.onDetach(); mCallbacks = sDummyCallbacks; } @Override public void onPause() { super.onPause(); mImageFetcher.flushCache(); } @Override public void onDestroy() { super.onDestroy(); mImageFetcher.closeCache(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_vendor_detail, null); mName = (TextView) rootView.findViewById(R.id.vendor_name); mLogo = (ImageView) rootView.findViewById(R.id.vendor_logo); mUrl = (TextView) rootView.findViewById(R.id.vendor_url); mDesc = (TextView) rootView.findViewById(R.id.vendor_desc); return rootView; } public void buildUiFromCursor(Cursor cursor) { if (getActivity() == null) { return; } if (!cursor.moveToFirst()) { return; } String nameString = cursor.getString(VendorsQuery.NAME); mName.setText(nameString); // Start background fetch to load vendor logo final String logoUrl = cursor.getString(VendorsQuery.LOGO_URL); if (!TextUtils.isEmpty(logoUrl)) { mImageFetcher.loadThumbnailImage(logoUrl, mLogo, R.drawable.sandbox_logo_empty); } mUrl.setText(cursor.getString(VendorsQuery.URL)); mDesc.setText(cursor.getString(VendorsQuery.DESC)); EasyTracker.getTracker().trackView("Sandbox Vendor: " + nameString); LOGD("Tracker", "Sandbox Vendor: " + nameString); mCallbacks.onTrackIdAvailable(cursor.getString(VendorsQuery.TRACK_ID)); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { return new CursorLoader(getActivity(), mVendorUri, VendorsQuery.PROJECTION, null, null, null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { buildUiFromCursor(cursor); } @Override public void onLoaderReset(Loader<Cursor> loader) { } /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Vendors} * query parameters. */ private interface VendorsQuery { int _TOKEN = 0x4; String[] PROJECTION = { ScheduleContract.Vendors.VENDOR_NAME, ScheduleContract.Vendors.VENDOR_DESC, ScheduleContract.Vendors.VENDOR_URL, ScheduleContract.Vendors.VENDOR_LOGO_URL, ScheduleContract.Vendors.TRACK_ID, }; int NAME = 0; int DESC = 1; int URL = 2; int LOGO_URL = 3; int TRACK_ID = 4; } }
1162584980-google-io
android/src/com/google/android/apps/iosched/ui/VendorDetailFragment.java
Java
asf20
6,277
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.BuildConfig; import com.google.android.apps.iosched.Config; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.gcm.ServerUtilities; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.gtv.GoogleTVSessionLivestreamActivity; import com.google.android.apps.iosched.util.AccountUtils; import com.google.android.apps.iosched.util.BeamUtils; import com.google.android.apps.iosched.util.HelpUtils; import com.google.android.apps.iosched.util.UIUtils; import com.google.android.gcm.GCMRegistrar; import com.google.api.client.googleapis.extensions.android2.auth.GoogleAccountManager; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import android.accounts.Account; import android.annotation.TargetApi; import android.app.SearchManager; import android.content.ContentResolver; import android.content.Intent; import android.content.SyncStatusObserver; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.ViewPager; import android.text.TextUtils; import android.widget.SearchView; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.LOGI; import static com.google.android.apps.iosched.util.LogUtils.LOGW; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * The landing screen for the app, once the user has logged in. * * <p>This activity uses different layouts to present its various fragments, depending on the * device configuration. {@link MyScheduleFragment}, {@link ExploreFragment}, and * {@link SocialStreamFragment} are always available to the user. {@link WhatsOnFragment} is * always available on tablets and phones in portrait, but is hidden on phones held in landscape. * * <p>On phone-size screens, the three fragments are represented by {@link ActionBar} tabs, and * can are held inside a {@link ViewPager} to allow horizontal swiping. * * <p>On tablets, the three fragments are always visible and are presented as either three panes * (landscape) or a grid (portrait). */ public class HomeActivity extends BaseActivity implements ActionBar.TabListener, ViewPager.OnPageChangeListener { private static final String TAG = makeLogTag(HomeActivity.class); private Object mSyncObserverHandle; private MyScheduleFragment mMyScheduleFragment; private ExploreFragment mExploreFragment; private SocialStreamFragment mSocialStreamFragment; private ViewPager mViewPager; private Menu mOptionsMenu; private AsyncTask<Void, Void, Void> mGCMRegisterTask; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // We're on Google TV; immediately short-circuit the normal behavior and show the // Google TV-specific landing page. if (UIUtils.isGoogleTV(this)) { Intent intent = new Intent(HomeActivity.this, GoogleTVSessionLivestreamActivity.class); startActivity(intent); finish(); } if (isFinishing()) { return; } UIUtils.enableDisableActivities(this); EasyTracker.getTracker().setContext(this); setContentView(R.layout.activity_home); FragmentManager fm = getSupportFragmentManager(); mViewPager = (ViewPager) findViewById(R.id.pager); String homeScreenLabel; if (mViewPager != null) { // Phone setup mViewPager.setAdapter(new HomePagerAdapter(getSupportFragmentManager())); mViewPager.setOnPageChangeListener(this); mViewPager.setPageMarginDrawable(R.drawable.grey_border_inset_lr); mViewPager.setPageMargin(getResources() .getDimensionPixelSize(R.dimen.page_margin_width)); final ActionBar actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); actionBar.addTab(actionBar.newTab() .setText(R.string.title_my_schedule) .setTabListener(this)); actionBar.addTab(actionBar.newTab() .setText(R.string.title_explore) .setTabListener(this)); actionBar.addTab(actionBar.newTab() .setText(R.string.title_stream) .setTabListener(this)); homeScreenLabel = getString(R.string.title_my_schedule); } else { mExploreFragment = (ExploreFragment) fm.findFragmentById(R.id.fragment_tracks); mMyScheduleFragment = (MyScheduleFragment) fm.findFragmentById( R.id.fragment_my_schedule); mSocialStreamFragment = (SocialStreamFragment) fm.findFragmentById(R.id.fragment_stream); homeScreenLabel = "Home"; } getSupportActionBar().setHomeButtonEnabled(false); EasyTracker.getTracker().trackView(homeScreenLabel); LOGD("Tracker", homeScreenLabel); // Sync data on load if (savedInstanceState == null) { triggerRefresh(); registerGCMClient(); } } private void registerGCMClient() { GCMRegistrar.checkDevice(this); if (BuildConfig.DEBUG) { GCMRegistrar.checkManifest(this); } final String regId = GCMRegistrar.getRegistrationId(this); if (TextUtils.isEmpty(regId)) { // Automatically registers application on startup. GCMRegistrar.register(this, Config.GCM_SENDER_ID); } else { // Device is already registered on GCM, check server. if (GCMRegistrar.isRegisteredOnServer(this)) { // Skips registration LOGI(TAG, "Already registered on the GCM server"); } else { // Try to register again, but not on the UI thread. // It's also necessary to cancel the task in onDestroy(). mGCMRegisterTask = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { boolean registered = ServerUtilities.register(HomeActivity.this, regId); if (!registered) { // At this point all attempts to register with the app // server failed, so we need to unregister the device // from GCM - the app will try to register again when // it is restarted. Note that GCM will send an // unregistered callback upon completion, but // GCMIntentService.onUnregistered() will ignore it. GCMRegistrar.unregister(HomeActivity.this); } return null; } @Override protected void onPostExecute(Void result) { mGCMRegisterTask = null; } }; mGCMRegisterTask.execute(null, null, null); } } } @Override protected void onDestroy() { super.onDestroy(); if (mGCMRegisterTask != null) { mGCMRegisterTask.cancel(true); } try { GCMRegistrar.onDestroy(this); } catch (Exception e) { LOGW(TAG, "GCM unregistration error", e); } } @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onPageScrolled(int i, float v, int i1) { } @Override public void onPageSelected(int position) { getSupportActionBar().setSelectedNavigationItem(position); int titleId = -1; switch (position) { case 0: titleId = R.string.title_my_schedule; break; case 1: titleId = R.string.title_explore; break; case 2: titleId = R.string.title_stream; break; } String title = getString(titleId); EasyTracker.getTracker().trackView(title); LOGD("Tracker", title); } @Override public void onPageScrollStateChanged(int i) { } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); // Since the pager fragments don't have known tags or IDs, the only way to persist the // reference is to use putFragment/getFragment. Remember, we're not persisting the exact // Fragment instance. This mechanism simply gives us a way to persist access to the // 'current' fragment instance for the given fragment (which changes across orientation // changes). // // The outcome of all this is that the "Refresh" menu button refreshes the stream across // orientation changes. if (mSocialStreamFragment != null) { getSupportFragmentManager().putFragment(outState, "stream_fragment", mSocialStreamFragment); } } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); if (mSocialStreamFragment == null) { mSocialStreamFragment = (SocialStreamFragment) getSupportFragmentManager() .getFragment(savedInstanceState, "stream_fragment"); } } private class HomePagerAdapter extends FragmentPagerAdapter { public HomePagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { switch (position) { case 0: return (mMyScheduleFragment = new MyScheduleFragment()); case 1: return (mExploreFragment = new ExploreFragment()); case 2: return (mSocialStreamFragment = new SocialStreamFragment()); } return null; } @Override public int getCount() { return 3; } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); mOptionsMenu = menu; getSupportMenuInflater().inflate(R.menu.home, menu); setupSearchMenuItem(menu); if (!BeamUtils.isBeamUnlocked(this)) { // Only show Beam unlocked after first Beam MenuItem beamItem = menu.findItem(R.id.menu_beam); if (beamItem != null) { menu.removeItem(beamItem.getItemId()); } } return true; } @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void setupSearchMenuItem(Menu menu) { MenuItem searchItem = menu.findItem(R.id.menu_search); if (searchItem != null && UIUtils.hasHoneycomb()) { SearchView searchView = (SearchView) searchItem.getActionView(); if (searchView != null) { SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE); searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); } } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_refresh: triggerRefresh(); return true; case R.id.menu_search: if (!UIUtils.hasHoneycomb()) { startSearch(null, false, Bundle.EMPTY, false); return true; } break; case R.id.menu_about: HelpUtils.showAbout(this); return true; case R.id.menu_sign_out: AccountUtils.signOut(this); finish(); return true; case R.id.menu_beam: Intent beamIntent = new Intent(this, BeamActivity.class); startActivity(beamIntent); return true; } return super.onOptionsItemSelected(item); } private void triggerRefresh() { Bundle extras = new Bundle(); extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); if (!UIUtils.isGoogleTV(this)) { ContentResolver.requestSync( new Account(AccountUtils.getChosenAccountName(this), GoogleAccountManager.ACCOUNT_TYPE), ScheduleContract.CONTENT_AUTHORITY, extras); } if (mSocialStreamFragment != null) { mSocialStreamFragment.refresh(); } } @Override protected void onPause() { super.onPause(); if (mSyncObserverHandle != null) { ContentResolver.removeStatusChangeListener(mSyncObserverHandle); mSyncObserverHandle = null; } } @Override protected void onResume() { super.onResume(); mSyncStatusObserver.onStatusChanged(0); // Watch for sync state changes final int mask = ContentResolver.SYNC_OBSERVER_TYPE_PENDING | ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE; mSyncObserverHandle = ContentResolver.addStatusChangeListener(mask, mSyncStatusObserver); } public void setRefreshActionButtonState(boolean refreshing) { if (mOptionsMenu == null) { return; } final MenuItem refreshItem = mOptionsMenu.findItem(R.id.menu_refresh); if (refreshItem != null) { if (refreshing) { refreshItem.setActionView(R.layout.actionbar_indeterminate_progress); } else { refreshItem.setActionView(null); } } } private final SyncStatusObserver mSyncStatusObserver = new SyncStatusObserver() { @Override public void onStatusChanged(int which) { runOnUiThread(new Runnable() { @Override public void run() { String accountName = AccountUtils.getChosenAccountName(HomeActivity.this); if (TextUtils.isEmpty(accountName)) { setRefreshActionButtonState(false); return; } Account account = new Account(accountName, GoogleAccountManager.ACCOUNT_TYPE); boolean syncActive = ContentResolver.isSyncActive( account, ScheduleContract.CONTENT_AUTHORITY); boolean syncPending = ContentResolver.isSyncPending( account, ScheduleContract.CONTENT_AUTHORITY); setRefreshActionButtonState(syncActive || syncPending); } }); } }; }
1162584980-google-io
android/src/com/google/android/apps/iosched/ui/HomeActivity.java
Java
asf20
16,365
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.tablet; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.BaseActivity; import com.google.android.apps.iosched.ui.SessionDetailFragment; import com.google.android.apps.iosched.ui.SessionsFragment; import com.google.android.apps.iosched.ui.TrackInfoHelperFragment; import com.google.android.apps.iosched.ui.VendorDetailFragment; import com.google.android.apps.iosched.ui.VendorsFragment; import com.google.android.apps.iosched.ui.widget.ShowHideMasterLayout; import com.google.android.apps.iosched.util.BeamUtils; import com.google.android.apps.iosched.util.UIUtils; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import android.annotation.TargetApi; import android.app.AlertDialog; import android.app.SearchManager; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.nfc.NfcAdapter; import android.nfc.NfcEvent; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.widget.SearchView; import static com.google.android.apps.iosched.util.LogUtils.LOGD; /** * A multi-pane activity, consisting of a {@link TracksDropdownFragment} (top-left), a * {@link SessionsFragment} or {@link VendorsFragment} (bottom-left), and * a {@link SessionDetailFragment} or {@link VendorDetailFragment} (right pane). */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class SessionsVendorsMultiPaneActivity extends BaseActivity implements ActionBar.TabListener, SessionsFragment.Callbacks, VendorsFragment.Callbacks, VendorDetailFragment.Callbacks, TracksDropdownFragment.Callbacks, TrackInfoHelperFragment.Callbacks { public static final String EXTRA_MASTER_URI = "com.google.android.apps.iosched.extra.MASTER_URI"; private static final String STATE_VIEW_TYPE = "view_type"; private TracksDropdownFragment mTracksDropdownFragment; private Fragment mDetailFragment; private boolean mFullUI = false; private ShowHideMasterLayout mShowHideMasterLayout; private String mViewType; private boolean mInitialTabSelect = true; @Override protected void onCreate(Bundle savedInstanceState) { if (BeamUtils.wasLaunchedThroughBeamFirstTime(this, getIntent())) { BeamUtils.setBeamUnlocked(this); showFirstBeamDialog(); } BeamUtils.tryUpdateIntentFromBeam(this); super.onCreate(savedInstanceState); trySetBeamCallback(); setContentView(R.layout.activity_sessions_vendors); final FragmentManager fm = getSupportFragmentManager(); mTracksDropdownFragment = (TracksDropdownFragment) fm.findFragmentById( R.id.fragment_tracks_dropdown); mShowHideMasterLayout = (ShowHideMasterLayout) findViewById(R.id.show_hide_master_layout); if (mShowHideMasterLayout != null) { mShowHideMasterLayout.setFlingToExposeMasterEnabled(true); } routeIntent(getIntent(), savedInstanceState != null); if (savedInstanceState != null) { if (mFullUI) { getSupportActionBar().setSelectedNavigationItem( TracksDropdownFragment.VIEW_TYPE_SESSIONS.equals( savedInstanceState.getString(STATE_VIEW_TYPE)) ? 0 : 1); } mDetailFragment = fm.findFragmentById(R.id.fragment_container_detail); updateDetailBackground(); } // This flag prevents onTabSelected from triggering extra master pane reloads // unless it's actually being triggered by the user (and not automatically by // the system) mInitialTabSelect = false; EasyTracker.getTracker().setContext(this); } private void routeIntent(Intent intent, boolean updateSurfaceOnly) { Uri uri = intent.getData(); if (uri == null) { return; } if (intent.hasExtra(Intent.EXTRA_TITLE)) { setTitle(intent.getStringExtra(Intent.EXTRA_TITLE)); } String mimeType = getContentResolver().getType(uri); if (ScheduleContract.Tracks.CONTENT_ITEM_TYPE.equals(mimeType)) { // Load track details showFullUI(true); if (!updateSurfaceOnly) { // TODO: don't assume the URI will contain the track ID String selectedTrackId = ScheduleContract.Tracks.getTrackId(uri); loadTrackList(TracksDropdownFragment.VIEW_TYPE_SESSIONS, selectedTrackId); onTrackSelected(selectedTrackId); if (mShowHideMasterLayout != null) { mShowHideMasterLayout.showMaster(true, ShowHideMasterLayout.FLAG_IMMEDIATE); } } } else if (ScheduleContract.Sessions.CONTENT_TYPE.equals(mimeType)) { // Load a session list, hiding the tracks dropdown and the tabs mViewType = TracksDropdownFragment.VIEW_TYPE_SESSIONS; showFullUI(false); if (!updateSurfaceOnly) { loadSessionList(uri, null); if (mShowHideMasterLayout != null) { mShowHideMasterLayout.showMaster(true, ShowHideMasterLayout.FLAG_IMMEDIATE); } } } else if (ScheduleContract.Sessions.CONTENT_ITEM_TYPE.equals(mimeType)) { // Load session details if (intent.hasExtra(EXTRA_MASTER_URI)) { mViewType = TracksDropdownFragment.VIEW_TYPE_SESSIONS; showFullUI(false); if (!updateSurfaceOnly) { loadSessionList((Uri) intent.getParcelableExtra(EXTRA_MASTER_URI), ScheduleContract.Sessions.getSessionId(uri)); loadSessionDetail(uri); } } else { mViewType = TracksDropdownFragment.VIEW_TYPE_SESSIONS; // prepare for onTrackInfo... showFullUI(true); if (!updateSurfaceOnly) { loadSessionDetail(uri); loadTrackInfoFromSessionUri(uri); } } } else if (ScheduleContract.Vendors.CONTENT_TYPE.equals(mimeType)) { // Load a vendor list mViewType = TracksDropdownFragment.VIEW_TYPE_VENDORS; showFullUI(false); if (!updateSurfaceOnly) { loadVendorList(uri, null); if (mShowHideMasterLayout != null) { mShowHideMasterLayout.showMaster(true, ShowHideMasterLayout.FLAG_IMMEDIATE); } } } else if (ScheduleContract.Vendors.CONTENT_ITEM_TYPE.equals(mimeType)) { // Load vendor details mViewType = TracksDropdownFragment.VIEW_TYPE_VENDORS; showFullUI(false); if (!updateSurfaceOnly) { Uri masterUri = (Uri) intent.getParcelableExtra(EXTRA_MASTER_URI); if (masterUri == null) { masterUri = ScheduleContract.Vendors.CONTENT_URI; } loadVendorList(masterUri, ScheduleContract.Vendors.getVendorId(uri)); loadVendorDetail(uri); } } updateDetailBackground(); } private void showFullUI(boolean fullUI) { mFullUI = fullUI; final ActionBar actionBar = getSupportActionBar(); final FragmentManager fm = getSupportFragmentManager(); if (fullUI) { actionBar.removeAllTabs(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); actionBar.setDisplayShowTitleEnabled(false); actionBar.addTab(actionBar.newTab() .setText(R.string.title_sessions) .setTag(TracksDropdownFragment.VIEW_TYPE_SESSIONS) .setTabListener(this)); actionBar.addTab(actionBar.newTab() .setText(R.string.title_vendors) .setTag(TracksDropdownFragment.VIEW_TYPE_VENDORS) .setTabListener(this)); fm.beginTransaction() .show(fm.findFragmentById(R.id.fragment_tracks_dropdown)) .commit(); } else { actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setDisplayShowTitleEnabled(true); fm.beginTransaction() .hide(fm.findFragmentById(R.id.fragment_tracks_dropdown)) .commit(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getSupportMenuInflater().inflate(R.menu.search, menu); MenuItem searchItem = menu.findItem(R.id.menu_search); if (searchItem != null && UIUtils.hasHoneycomb()) { SearchView searchView = (SearchView) searchItem.getActionView(); if (searchView != null) { SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE); searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); } } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: if (mShowHideMasterLayout != null && !mShowHideMasterLayout.isMasterVisible()) { // If showing the detail view, pressing Up should show the master pane. mShowHideMasterLayout.showMaster(true, 0); return true; } break; case R.id.menu_search: if (!UIUtils.hasHoneycomb()) { startSearch(null, false, Bundle.EMPTY, false); return true; } break; } return super.onOptionsItemSelected(item); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(STATE_VIEW_TYPE, mViewType); } @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { loadTrackList((String) tab.getTag()); if (!mInitialTabSelect) { onTrackSelected(mTracksDropdownFragment.getSelectedTrackId()); if (mShowHideMasterLayout != null) { mShowHideMasterLayout.showMaster(true, 0); } } } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } private void loadTrackList(String viewType) { loadTrackList(viewType, null); } private void loadTrackList(String viewType, String selectTrackId) { if (mDetailFragment != null && !mViewType.equals(viewType)) { getSupportFragmentManager().beginTransaction() .remove(mDetailFragment) .commit(); mDetailFragment = null; } mViewType = viewType; if (selectTrackId != null) { mTracksDropdownFragment.loadTrackList(viewType, selectTrackId); } else { mTracksDropdownFragment.loadTrackList(viewType); } updateDetailBackground(); } private void updateDetailBackground() { if (mDetailFragment == null) { if (TracksDropdownFragment.VIEW_TYPE_SESSIONS.equals(mViewType)) { findViewById(R.id.fragment_container_detail).setBackgroundResource( R.drawable.grey_frame_on_white_empty_sessions); } else { findViewById(R.id.fragment_container_detail).setBackgroundResource( R.drawable.grey_frame_on_white_empty_sandbox); } } else { findViewById(R.id.fragment_container_detail).setBackgroundResource( R.drawable.grey_frame_on_white); } } private void loadSessionList(Uri sessionsUri, String selectSessionId) { SessionsFragment fragment = new SessionsFragment(); fragment.setSelectedSessionId(selectSessionId); fragment.setArguments(BaseActivity.intentToFragmentArguments( new Intent(Intent.ACTION_VIEW, sessionsUri))); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container_master, fragment) .commit(); } private void loadSessionDetail(Uri sessionUri) { BeamUtils.setBeamSessionUri(this, sessionUri); SessionDetailFragment fragment = new SessionDetailFragment(); fragment.setArguments(BaseActivity.intentToFragmentArguments( new Intent(Intent.ACTION_VIEW, sessionUri))); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container_detail, fragment) .commit(); mDetailFragment = fragment; updateDetailBackground(); // If loading session details in portrait, hide the master pane if (mShowHideMasterLayout != null) { mShowHideMasterLayout.showMaster(false, 0); } } private void loadVendorList(Uri vendorsUri, String selectVendorId) { VendorsFragment fragment = new VendorsFragment(); fragment.setSelectedVendorId(selectVendorId); fragment.setArguments(BaseActivity.intentToFragmentArguments( new Intent(Intent.ACTION_VIEW, vendorsUri))); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container_master, fragment) .commit(); } private void loadVendorDetail(Uri vendorUri) { VendorDetailFragment fragment = new VendorDetailFragment(); fragment.setArguments(BaseActivity.intentToFragmentArguments( new Intent(Intent.ACTION_VIEW, vendorUri))); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container_detail, fragment) .commit(); mDetailFragment = fragment; updateDetailBackground(); // If loading session details in portrait, hide the master pane if (mShowHideMasterLayout != null) { mShowHideMasterLayout.showMaster(false, 0); } } @Override public void onTrackNameAvailable(String trackId, String trackName) { String trackType; if (TracksDropdownFragment.VIEW_TYPE_SESSIONS.equals(mViewType)) { trackType = getString(R.string.title_sessions); } else { trackType = getString(R.string.title_vendors); } EasyTracker.getTracker().trackView(trackType + ": " + getTitle()); LOGD("Tracker", trackType + ": " + mTracksDropdownFragment.getTrackName()); } @Override public void onTrackSelected(String trackId) { boolean allTracks = (ScheduleContract.Tracks.ALL_TRACK_ID.equals(trackId)); if (TracksDropdownFragment.VIEW_TYPE_SESSIONS.equals(mViewType)) { loadSessionList(allTracks ? ScheduleContract.Sessions.CONTENT_URI : ScheduleContract.Tracks.buildSessionsUri(trackId), null); } else { loadVendorList(allTracks ? ScheduleContract.Vendors.CONTENT_URI : ScheduleContract.Tracks.buildVendorsUri(trackId), null); } } @Override public boolean onSessionSelected(String sessionId) { loadSessionDetail(ScheduleContract.Sessions.buildSessionUri(sessionId)); return true; } @Override public boolean onVendorSelected(String vendorId) { loadVendorDetail(ScheduleContract.Vendors.buildVendorUri(vendorId)); return true; } private TrackInfoHelperFragment mTrackInfoHelperFragment; private String mTrackInfoLoadCookie; private void loadTrackInfoFromSessionUri(Uri sessionUri) { mTrackInfoLoadCookie = ScheduleContract.Sessions.getSessionId(sessionUri); Uri trackDirUri = ScheduleContract.Sessions.buildTracksDirUri( ScheduleContract.Sessions.getSessionId(sessionUri)); android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); if (mTrackInfoHelperFragment != null) { ft.remove(mTrackInfoHelperFragment); } mTrackInfoHelperFragment = TrackInfoHelperFragment.newFromTrackUri(trackDirUri); ft.add(mTrackInfoHelperFragment, "track_info").commit(); } @Override public void onTrackInfoAvailable(String trackId, String trackName, int trackColor) { loadTrackList(mViewType, trackId); boolean allTracks = (ScheduleContract.Tracks.ALL_TRACK_ID.equals(trackId)); if (TracksDropdownFragment.VIEW_TYPE_SESSIONS.equals(mViewType)) { loadSessionList(allTracks ? ScheduleContract.Sessions.CONTENT_URI : ScheduleContract.Tracks.buildSessionsUri(trackId), mTrackInfoLoadCookie); } else { loadVendorList(allTracks ? ScheduleContract.Vendors.CONTENT_URI : ScheduleContract.Tracks.buildVendorsUri(trackId), mTrackInfoLoadCookie); } } @Override public void onTrackIdAvailable(String trackId) { } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) private void trySetBeamCallback() { if (UIUtils.hasICS()) { BeamUtils.setBeamCompleteCallback(this, new NfcAdapter.OnNdefPushCompleteCallback() { @Override public void onNdefPushComplete(NfcEvent event) { // Beam has been sent if (!BeamUtils.isBeamUnlocked(SessionsVendorsMultiPaneActivity.this)) { BeamUtils.setBeamUnlocked(SessionsVendorsMultiPaneActivity.this); runOnUiThread(new Runnable() { @Override public void run() { showFirstBeamDialog(); } }); } } }); } } private void showFirstBeamDialog() { new AlertDialog.Builder(this) .setTitle(R.string.just_beamed) .setMessage(R.string.beam_unlocked_session) .setNegativeButton(R.string.close, null) .setPositiveButton(R.string.view_beam_session, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { BeamUtils.launchBeamSession(SessionsVendorsMultiPaneActivity.this); di.dismiss(); } }) .create() .show(); } }
1162584980-google-io
android/src/com/google/android/apps/iosched/ui/tablet/SessionsVendorsMultiPaneActivity.java
Java
asf20
20,162
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.tablet; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.TracksAdapter; import com.google.android.apps.iosched.util.UIUtils; import com.actionbarsherlock.app.SherlockFragment; import android.annotation.TargetApi; import android.app.Activity; import android.content.res.Resources; import android.database.Cursor; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListPopupWindow; import android.widget.PopupWindow; import android.widget.TextView; /** * A tablet-specific fragment that emulates a giant {@link android.widget.Spinner}-like widget. * When touched, it shows a {@link ListPopupWindow} containing a list of tracks, * using {@link TracksAdapter}. Requires API level 11 or later since {@link ListPopupWindow} is * API level 11+. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class TracksDropdownFragment extends SherlockFragment implements LoaderManager.LoaderCallbacks<Cursor>, AdapterView.OnItemClickListener, PopupWindow.OnDismissListener { public static final String VIEW_TYPE_SESSIONS = "sessions"; public static final String VIEW_TYPE_VENDORS = "vendors"; private static final String STATE_VIEW_TYPE = "viewType"; private static final String STATE_SELECTED_TRACK_ID = "selectedTrackId"; private TracksAdapter mAdapter; private String mViewType; private Handler mHandler = new Handler(); private ListPopupWindow mListPopupWindow; private ViewGroup mRootView; private TextView mTitle; private TextView mAbstract; private String mTrackId; public interface Callbacks { public void onTrackSelected(String trackId); public void onTrackNameAvailable(String trackId, String trackName); } private static Callbacks sDummyCallbacks = new Callbacks() { @Override public void onTrackSelected(String trackId) { } @Override public void onTrackNameAvailable(String trackId, String trackName) {} }; private Callbacks mCallbacks = sDummyCallbacks; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mAdapter = new TracksAdapter(getActivity()); if (savedInstanceState != null) { // Since this fragment doesn't rely on fragment arguments, we must // handle // state restores and saves ourselves. mViewType = savedInstanceState.getString(STATE_VIEW_TYPE); mTrackId = savedInstanceState.getString(STATE_SELECTED_TRACK_ID); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(STATE_VIEW_TYPE, mViewType); outState.putString(STATE_SELECTED_TRACK_ID, mTrackId); } public String getSelectedTrackId() { return mTrackId; } public void selectTrack(String trackId) { loadTrackList(mViewType, trackId); } public void loadTrackList(String viewType) { loadTrackList(viewType, mTrackId); } public void loadTrackList(String viewType, String selectTrackId) { // Teardown from previous arguments if (mListPopupWindow != null) { mListPopupWindow.setAdapter(null); } mViewType = viewType; mTrackId = selectTrackId; // Start background query to load tracks getLoaderManager().restartLoader(TracksAdapter.TracksQuery._TOKEN, null, this); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = (ViewGroup) inflater.inflate(R.layout.fragment_tracks_dropdown, null); mTitle = (TextView) mRootView.findViewById(R.id.track_title); mAbstract = (TextView) mRootView.findViewById(R.id.track_abstract); mRootView.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { mListPopupWindow = new ListPopupWindow(getActivity()); mListPopupWindow.setAdapter(mAdapter); mListPopupWindow.setModal(true); mListPopupWindow.setContentWidth( getResources().getDimensionPixelSize(R.dimen.track_dropdown_width)); mListPopupWindow.setAnchorView(mRootView); mListPopupWindow.setOnItemClickListener(TracksDropdownFragment.this); mListPopupWindow.show(); mListPopupWindow.setOnDismissListener(TracksDropdownFragment.this); } }); return mRootView; } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (!(activity instanceof Callbacks)) { throw new ClassCastException("Activity must implement fragment's callbacks."); } mCallbacks = (Callbacks) activity; } @Override public void onDetach() { super.onDetach(); mCallbacks = sDummyCallbacks; if (mListPopupWindow != null) { mListPopupWindow.dismiss(); } } /** {@inheritDoc} */ public void onItemClick(AdapterView<?> parent, View view, int position, long id) { final Cursor cursor = (Cursor) mAdapter.getItem(position); loadTrack(cursor, true); if (mListPopupWindow != null) { mListPopupWindow.dismiss(); } } public String getTrackName() { return (String) mTitle.getText(); } private void loadTrack(Cursor cursor, boolean triggerCallback) { final int trackColor; final Resources res = getResources(); if (cursor != null) { trackColor = cursor.getInt(TracksAdapter.TracksQuery.TRACK_COLOR); mTrackId = cursor.getString(TracksAdapter.TracksQuery.TRACK_ID); mTitle.setText(cursor.getString(TracksAdapter.TracksQuery.TRACK_NAME)); mAbstract.setText(cursor.getString(TracksAdapter.TracksQuery.TRACK_ABSTRACT)); } else { trackColor = res.getColor(R.color.all_track_color); mTrackId = ScheduleContract.Tracks.ALL_TRACK_ID; mTitle.setText(VIEW_TYPE_SESSIONS.equals(mViewType) ? R.string.all_tracks_sessions : R.string.all_tracks_vendors); mAbstract.setText(VIEW_TYPE_SESSIONS.equals(mViewType) ? R.string.all_tracks_subtitle_sessions : R.string.all_tracks_subtitle_vendors); } boolean isDark = UIUtils.isColorDark(trackColor); mRootView.setBackgroundColor(trackColor); if (isDark) { mTitle.setTextColor(res.getColor(R.color.body_text_1_inverse)); mAbstract.setTextColor(res.getColor(R.color.body_text_2_inverse)); mRootView.findViewById(R.id.track_dropdown_arrow).setBackgroundResource( R.drawable.track_dropdown_arrow_light); } else { mTitle.setTextColor(res.getColor(R.color.body_text_1)); mAbstract.setTextColor(res.getColor(R.color.body_text_2)); mRootView.findViewById(R.id.track_dropdown_arrow).setBackgroundResource( R.drawable.track_dropdown_arrow_dark); } mCallbacks.onTrackNameAvailable(mTrackId, mTitle.getText().toString()); if (triggerCallback) { mHandler.post(new Runnable() { @Override public void run() { mCallbacks.onTrackSelected(mTrackId); } }); } } public void onDismiss() { mListPopupWindow = null; } @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { // Filter our tracks query to only include those with valid results String[] projection = TracksAdapter.TracksQuery.PROJECTION; String selection = null; if (VIEW_TYPE_SESSIONS.equals(mViewType)) { // Only show tracks with at least one session projection = TracksAdapter.TracksQuery.PROJECTION_WITH_SESSIONS_COUNT; selection = ScheduleContract.Tracks.SESSIONS_COUNT + ">0"; } else if (VIEW_TYPE_VENDORS.equals(mViewType)) { // Only show tracks with at least one vendor projection = TracksAdapter.TracksQuery.PROJECTION_WITH_VENDORS_COUNT; selection = ScheduleContract.Tracks.VENDORS_COUNT + ">0"; } return new CursorLoader(getActivity(), ScheduleContract.Tracks.CONTENT_URI, projection, selection, null, ScheduleContract.Tracks.DEFAULT_SORT); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if (getActivity() == null || cursor == null) { return; } boolean trackLoaded = false; if (mTrackId != null) { cursor.moveToFirst(); while (!cursor.isAfterLast()) { if (mTrackId.equals(cursor.getString(TracksAdapter.TracksQuery.TRACK_ID))) { loadTrack(cursor, false); trackLoaded = true; break; } cursor.moveToNext(); } } if (!trackLoaded) { loadTrack(null, false); } mAdapter.setHasAllItem(true); mAdapter.changeCursor(cursor); } @Override public void onLoaderReset(Loader<Cursor> cursor) { } }
1162584980-google-io
android/src/com/google/android/apps/iosched/ui/tablet/TracksDropdownFragment.java
Java
asf20
10,527
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.tablet; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.BaseActivity; import com.google.android.apps.iosched.ui.MapFragment; import com.google.android.apps.iosched.ui.SessionDetailFragment; import com.google.android.apps.iosched.ui.SessionsFragment; import com.google.android.apps.iosched.ui.VendorDetailFragment; import com.google.android.apps.iosched.ui.VendorsFragment; import android.annotation.TargetApi; import android.app.FragmentBreadCrumbs; import android.content.Intent; import android.content.res.Configuration; import android.database.Cursor; import android.os.Build; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; /** * A multi-pane activity, where the full-screen content is a {@link MapFragment} and popup content * may be visible at any given time, containing either a {@link SessionsFragment} (representing * sessions for a given room) or a {@link SessionDetailFragment}. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class MapMultiPaneActivity extends BaseActivity implements FragmentManager.OnBackStackChangedListener, MapFragment.Callbacks, SessionsFragment.Callbacks, LoaderManager.LoaderCallbacks<Cursor> { private boolean mPauseBackStackWatcher = false; private FragmentBreadCrumbs mFragmentBreadCrumbs; private String mSelectedRoomName; private MapFragment mMapFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_map); FragmentManager fm = getSupportFragmentManager(); fm.addOnBackStackChangedListener(this); mFragmentBreadCrumbs = (FragmentBreadCrumbs) findViewById(R.id.breadcrumbs); mFragmentBreadCrumbs.setActivity(this); mMapFragment = (MapFragment) fm.findFragmentByTag("map"); if (mMapFragment == null) { mMapFragment = new MapFragment(); mMapFragment.setArguments(intentToFragmentArguments(getIntent())); fm.beginTransaction() .add(R.id.fragment_container_map, mMapFragment, "map") .commit(); } findViewById(R.id.close_button).setOnClickListener(new View.OnClickListener() { public void onClick(View view) { clearBackStack(false); } }); updateBreadCrumbs(); onConfigurationChanged(getResources().getConfiguration()); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); boolean landscape = (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE); LinearLayout spacerView = (LinearLayout) findViewById(R.id.map_detail_spacer); spacerView.setOrientation(landscape ? LinearLayout.HORIZONTAL : LinearLayout.VERTICAL); spacerView.setGravity(landscape ? Gravity.RIGHT : Gravity.BOTTOM); View popupView = findViewById(R.id.map_detail_popup); LinearLayout.LayoutParams popupLayoutParams = (LinearLayout.LayoutParams) popupView.getLayoutParams(); popupLayoutParams.width = landscape ? 0 : ViewGroup.LayoutParams.MATCH_PARENT; popupLayoutParams.height = landscape ? ViewGroup.LayoutParams.MATCH_PARENT : 0; popupView.setLayoutParams(popupLayoutParams); popupView.requestLayout(); } private void clearBackStack(boolean pauseWatcher) { if (pauseWatcher) { mPauseBackStackWatcher = true; } FragmentManager fm = getSupportFragmentManager(); while (fm.getBackStackEntryCount() > 0) { fm.popBackStackImmediate(); } if (pauseWatcher) { mPauseBackStackWatcher = false; } } public void onBackStackChanged() { if (mPauseBackStackWatcher) { return; } if (getSupportFragmentManager().getBackStackEntryCount() == 0) { showDetailPane(false); } updateBreadCrumbs(); } private void showDetailPane(boolean show) { View detailPopup = findViewById(R.id.map_detail_spacer); if (show != (detailPopup.getVisibility() == View.VISIBLE)) { detailPopup.setVisibility(show ? View.VISIBLE : View.GONE); // Pan the map left or up depending on the orientation. boolean landscape = getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE; mMapFragment.panBy( landscape ? (show ? 0.25f : -0.25f) : 0, landscape ? 0 : (show ? 0.25f : -0.25f)); } } public void updateBreadCrumbs() { final String title = (mSelectedRoomName != null) ? mSelectedRoomName : getString(R.string.title_sessions); final String detailTitle = getString(R.string.title_session_detail); if (getSupportFragmentManager().getBackStackEntryCount() >= 2) { mFragmentBreadCrumbs.setParentTitle(title, title, mFragmentBreadCrumbsClickListener); mFragmentBreadCrumbs.setTitle(detailTitle, detailTitle); } else { mFragmentBreadCrumbs.setParentTitle(null, null, null); mFragmentBreadCrumbs.setTitle(title, title); } } private View.OnClickListener mFragmentBreadCrumbsClickListener = new View.OnClickListener() { @Override public void onClick(View view) { getSupportFragmentManager().popBackStack(); } }; @Override public void onRoomSelected(String roomId) { // Load room details mSelectedRoomName = null; Bundle loadRoomDataArgs = new Bundle(); loadRoomDataArgs.putString("room_id", roomId); getSupportLoaderManager().restartLoader(0, loadRoomDataArgs, this); // force load // Show the sessions in the room clearBackStack(true); showDetailPane(true); SessionsFragment fragment = new SessionsFragment(); fragment.setArguments(BaseActivity.intentToFragmentArguments( new Intent(Intent.ACTION_VIEW, ScheduleContract.Rooms.buildSessionsDirUri(roomId)))); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container_detail, fragment) .addToBackStack(null) .commit(); updateBreadCrumbs(); } @Override public boolean onSessionSelected(String sessionId) { // Show the session details showDetailPane(true); SessionDetailFragment fragment = new SessionDetailFragment(); Intent intent = new Intent(Intent.ACTION_VIEW, ScheduleContract.Sessions.buildSessionUri(sessionId)); intent.putExtra(SessionDetailFragment.EXTRA_VARIABLE_HEIGHT_HEADER, true); fragment.setArguments(BaseActivity.intentToFragmentArguments(intent)); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container_detail, fragment) .addToBackStack(null) .commit(); updateBreadCrumbs(); return false; } @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { return new CursorLoader(this, ScheduleContract.Rooms.buildRoomUri(data.getString("room_id")), RoomsQuery.PROJECTION, null, null, null); } @Override public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) { try { if (!cursor.moveToFirst()) { return; } mSelectedRoomName = cursor.getString(RoomsQuery.ROOM_NAME); updateBreadCrumbs(); } finally { cursor.close(); } } @Override public void onLoaderReset(Loader<Cursor> loader) { } private interface RoomsQuery { String[] PROJECTION = { ScheduleContract.Rooms.ROOM_ID, ScheduleContract.Rooms.ROOM_NAME, ScheduleContract.Rooms.ROOM_FLOOR, }; int ROOM_ID = 0; int ROOM_NAME = 1; int ROOM_FLOOR = 2; } }
1162584980-google-io
android/src/com/google/android/apps/iosched/ui/tablet/MapMultiPaneActivity.java
Java
asf20
9,250
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.phone; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.SessionsFragment; import com.google.android.apps.iosched.ui.SimpleSinglePaneActivity; import com.google.android.apps.iosched.util.UIUtils; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import android.annotation.TargetApi; import android.app.SearchManager; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.widget.SearchView; /** * A single-pane activity that shows a {@link SessionsFragment} containing a list of sessions. * This is used when showing the sessions for a given time slot, or showing session search results. */ public class SessionsActivity extends SimpleSinglePaneActivity implements SessionsFragment.Callbacks { @Override protected Fragment onCreatePane() { return new SessionsFragment(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getSupportMenuInflater().inflate(R.menu.search, menu); setupSearchMenuItem(menu); return true; } @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void setupSearchMenuItem(Menu menu) { MenuItem searchItem = menu.findItem(R.id.menu_search); if (searchItem != null && UIUtils.hasHoneycomb()) { SearchView searchView = (SearchView) searchItem.getActionView(); if (searchView != null) { SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE); searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); } } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_search: if (!UIUtils.hasHoneycomb()) { startSearch(null, false, Bundle.EMPTY, false); return true; } break; } return super.onOptionsItemSelected(item); } @Override public boolean onSessionSelected(String sessionId) { startActivity(new Intent(Intent.ACTION_VIEW, ScheduleContract.Sessions.buildSessionUri(sessionId))); return false; } }
1162584980-google-io
android/src/com/google/android/apps/iosched/ui/phone/SessionsActivity.java
Java
asf20
3,083
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.phone; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.MapFragment; import com.google.android.apps.iosched.ui.SimpleSinglePaneActivity; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; /** * A single-pane activity that shows a {@link MapFragment}. */ public class MapActivity extends SimpleSinglePaneActivity implements MapFragment.Callbacks, LoaderManager.LoaderCallbacks<Cursor> { @Override protected Fragment onCreatePane() { return new MapFragment(); } @Override public void onRoomSelected(String roomId) { Bundle loadRoomDataArgs = new Bundle(); loadRoomDataArgs.putString("room_id", roomId); // force load (don't use previously used data) getSupportLoaderManager().restartLoader(0, loadRoomDataArgs, this); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { return new CursorLoader(this, ScheduleContract.Rooms.buildRoomUri(data.getString("room_id")), RoomsQuery.PROJECTION, null, null, null); } @Override public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) { try { if (!cursor.moveToFirst()) { return; } Intent roomIntent = new Intent(Intent.ACTION_VIEW, ScheduleContract.Rooms.buildSessionsDirUri( cursor.getString(RoomsQuery.ROOM_ID))); roomIntent.putExtra(Intent.EXTRA_TITLE, cursor.getString(RoomsQuery.ROOM_NAME)); startActivity(roomIntent); } finally { cursor.close(); } } @Override public void onLoaderReset(Loader<Cursor> loader) { } private interface RoomsQuery { String[] PROJECTION = { ScheduleContract.Rooms.ROOM_ID, ScheduleContract.Rooms.ROOM_NAME, ScheduleContract.Rooms.ROOM_FLOOR, }; int ROOM_ID = 0; int ROOM_NAME = 1; int ROOM_FLOOR = 2; } }
1162584980-google-io
android/src/com/google/android/apps/iosched/ui/phone/MapActivity.java
Java
asf20
2,964
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.phone; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.BaseActivity; import com.google.android.apps.iosched.ui.SessionsFragment; import com.google.android.apps.iosched.ui.SocialStreamActivity; import com.google.android.apps.iosched.ui.SocialStreamFragment; import com.google.android.apps.iosched.ui.TrackInfoHelperFragment; import com.google.android.apps.iosched.ui.VendorsFragment; import com.google.android.apps.iosched.util.UIUtils; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.ViewPager; import static com.google.android.apps.iosched.util.LogUtils.LOGD; /** * A single-pane activity that shows a {@link SessionsFragment} in one tab and a * {@link VendorsFragment} in another tab, representing the sessions and developer sandbox companies * for the given conference track (Android, Chrome, etc.). */ public class TrackDetailActivity extends BaseActivity implements ActionBar.TabListener, ViewPager.OnPageChangeListener, SessionsFragment.Callbacks, VendorsFragment.Callbacks, TrackInfoHelperFragment.Callbacks { private ViewPager mViewPager; private String mTrackId; private Uri mTrackUri; private boolean mShowVendors = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_track_detail); mTrackUri = getIntent().getData(); mTrackId = ScheduleContract.Tracks.getTrackId(mTrackUri); mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(new TrackDetailPagerAdapter(getSupportFragmentManager())); mViewPager.setOnPageChangeListener(this); mViewPager.setPageMarginDrawable(R.drawable.grey_border_inset_lr); mViewPager.setPageMargin(getResources().getDimensionPixelSize(R.dimen.page_margin_width)); mShowVendors = !ScheduleContract.Tracks.CODELABS_TRACK_ID.equals(mTrackId) && !ScheduleContract.Tracks.TECH_TALK_TRACK_ID.equals(mTrackId); if (mShowVendors) { final ActionBar actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); actionBar.addTab(actionBar.newTab() .setText(R.string.title_sessions) .setTabListener(this)); actionBar.addTab(actionBar.newTab() .setText(R.string.title_vendors) .setTabListener(this)); } if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(TrackInfoHelperFragment.newFromTrackUri(mTrackUri), "track_info") .commit(); } } @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onPageScrolled(int i, float v, int i1) { } @Override public void onPageSelected(int position) { getSupportActionBar().setSelectedNavigationItem(position); int titleId = -1; switch (position) { case 0: titleId = R.string.title_sessions; break; case 1: titleId = R.string.title_vendors; break; } String title = getString(titleId); EasyTracker.getTracker().trackView(title + ": " + getTitle()); LOGD("Tracker", title + ": " + getTitle()); } @Override public void onPageScrollStateChanged(int i) { } private class TrackDetailPagerAdapter extends FragmentPagerAdapter { public TrackDetailPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { boolean allTracks = (ScheduleContract.Tracks.ALL_TRACK_ID.equals(mTrackId)); if (position == 0) { Fragment fragment = new SessionsFragment(); fragment.setArguments(BaseActivity.intentToFragmentArguments(new Intent( Intent.ACTION_VIEW, allTracks ? ScheduleContract.Sessions.CONTENT_URI : ScheduleContract.Tracks.buildSessionsUri(mTrackId)))); return fragment; } else { Fragment fragment = new VendorsFragment(); fragment.setArguments(BaseActivity.intentToFragmentArguments(new Intent( Intent.ACTION_VIEW, allTracks ? ScheduleContract.Vendors.CONTENT_URI : ScheduleContract.Tracks.buildVendorsUri(mTrackId)))); return fragment; } } @Override public int getCount() { return mShowVendors ? 2 : 1; } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getSupportMenuInflater().inflate(R.menu.track_detail, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_social_stream: Intent intent = new Intent(this, SocialStreamActivity.class); intent.putExtra(SocialStreamFragment.EXTRA_QUERY, UIUtils.getSessionHashtagsString(mTrackId)); startActivity(intent); break; } return super.onOptionsItemSelected(item); } @Override public void onTrackInfoAvailable(String trackId, String trackName, int trackColor) { setTitle(trackName); setActionBarColor(trackColor); EasyTracker.getTracker().trackView(getString(R.string.title_sessions) + ": " + getTitle()); LOGD("Tracker", getString(R.string.title_sessions) + ": " + getTitle()); } @Override public boolean onSessionSelected(String sessionId) { startActivity(new Intent(Intent.ACTION_VIEW, ScheduleContract.Sessions.buildSessionUri(sessionId))); return false; } @Override public boolean onVendorSelected(String vendorId) { startActivity(new Intent(Intent.ACTION_VIEW, ScheduleContract.Vendors.buildVendorUri(vendorId))); return false; } }
1162584980-google-io
android/src/com/google/android/apps/iosched/ui/phone/TrackDetailActivity.java
Java
asf20
7,891
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.phone; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.HomeActivity; import com.google.android.apps.iosched.ui.SimpleSinglePaneActivity; import com.google.android.apps.iosched.ui.TrackInfoHelperFragment; import com.google.android.apps.iosched.ui.VendorDetailFragment; import com.actionbarsherlock.view.MenuItem; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.NavUtils; /** * A single-pane activity that shows a {@link VendorDetailFragment}. */ public class VendorDetailActivity extends SimpleSinglePaneActivity implements VendorDetailFragment.Callbacks, TrackInfoHelperFragment.Callbacks { private String mTrackId = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override protected Fragment onCreatePane() { return new VendorDetailFragment(); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { // Up to this session's track details, or Home if no track is available Intent parentIntent; if (mTrackId != null) { parentIntent = new Intent(Intent.ACTION_VIEW, ScheduleContract.Tracks.buildTrackUri(mTrackId)); } else { parentIntent = new Intent(this, HomeActivity.class); } NavUtils.navigateUpTo(this, parentIntent); return true; } return super.onOptionsItemSelected(item); } @Override public void onTrackInfoAvailable(String trackId, String trackName, int trackColor) { mTrackId = trackId; setTitle(trackName); setActionBarColor(trackColor); } @Override public void onTrackIdAvailable(final String trackId) { new Handler().post(new Runnable() { @Override public void run() { FragmentManager fm = getSupportFragmentManager(); if (fm.findFragmentByTag("track_info") == null) { fm.beginTransaction() .add(TrackInfoHelperFragment.newFromTrackUri( ScheduleContract.Tracks.buildTrackUri(trackId)), "track_info") .commit(); } } }); } }
1162584980-google-io
android/src/com/google/android/apps/iosched/ui/phone/VendorDetailActivity.java
Java
asf20
3,248
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.phone; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.HomeActivity; import com.google.android.apps.iosched.ui.SessionDetailFragment; import com.google.android.apps.iosched.ui.SimpleSinglePaneActivity; import com.google.android.apps.iosched.ui.TrackInfoHelperFragment; import com.google.android.apps.iosched.util.BeamUtils; import com.google.android.apps.iosched.util.UIUtils; import com.actionbarsherlock.view.MenuItem; import android.annotation.TargetApi; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.nfc.NfcAdapter; import android.nfc.NfcEvent; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.NavUtils; /** * A single-pane activity that shows a {@link SessionDetailFragment}. */ public class SessionDetailActivity extends SimpleSinglePaneActivity implements TrackInfoHelperFragment.Callbacks { private String mTrackId = null; @Override protected void onCreate(Bundle savedInstanceState) { if (BeamUtils.wasLaunchedThroughBeamFirstTime(this, getIntent())) { BeamUtils.setBeamUnlocked(this); showFirstBeamDialog(); } BeamUtils.tryUpdateIntentFromBeam(this); super.onCreate(savedInstanceState); if (savedInstanceState == null) { Uri sessionUri = getIntent().getData(); BeamUtils.setBeamSessionUri(this, sessionUri); trySetBeamCallback(); getSupportFragmentManager().beginTransaction() .add(TrackInfoHelperFragment.newFromSessionUri(sessionUri), "track_info") .commit(); } } @Override protected Fragment onCreatePane() { return new SessionDetailFragment(); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { // Up to this session's track details, or Home if no track is available Intent parentIntent; if (mTrackId != null) { parentIntent = new Intent(Intent.ACTION_VIEW, ScheduleContract.Tracks.buildTrackUri(mTrackId)); } else { parentIntent = new Intent(this, HomeActivity.class); } NavUtils.navigateUpTo(this, parentIntent); return true; } return super.onOptionsItemSelected(item); } @Override public void onTrackInfoAvailable(String trackId, String trackName, int trackColor) { mTrackId = trackId; setTitle(trackName); setActionBarColor(trackColor); } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) private void trySetBeamCallback() { if (UIUtils.hasICS()) { BeamUtils.setBeamCompleteCallback(this, new NfcAdapter.OnNdefPushCompleteCallback() { @Override public void onNdefPushComplete(NfcEvent event) { // Beam has been sent if (!BeamUtils.isBeamUnlocked(SessionDetailActivity.this)) { BeamUtils.setBeamUnlocked(SessionDetailActivity.this); runOnUiThread(new Runnable() { @Override public void run() { showFirstBeamDialog(); } }); } } }); } } private void showFirstBeamDialog() { new AlertDialog.Builder(this) .setTitle(R.string.just_beamed) .setMessage(R.string.beam_unlocked_session) .setNegativeButton(R.string.close, null) .setPositiveButton(R.string.view_beam_session, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { BeamUtils.launchBeamSession(SessionDetailActivity.this); di.dismiss(); } }) .create() .show(); } }
1162584980-google-io
android/src/com/google/android/apps/iosched/ui/phone/SessionDetailActivity.java
Java
asf20
5,069
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.Config; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.util.ImageFetcher; import com.google.android.apps.iosched.util.UIUtils; import com.google.api.client.googleapis.services.GoogleKeyInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.http.json.JsonHttpRequestInitializer; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson.JacksonFactory; import com.google.api.services.plus.Plus; import com.google.api.services.plus.model.Activity; import com.google.api.services.plus.model.ActivityFeed; import com.actionbarsherlock.app.SherlockListFragment; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.graphics.Color; import android.net.ParseException; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.LoaderManager; import android.support.v4.app.ShareCompat; import android.support.v4.content.AsyncTaskLoader; import android.support.v4.content.Loader; import android.text.Html; import android.text.TextUtils; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.widget.AbsListView; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * A {@link WebView}-based fragment that shows Google+ public search results for a given query, * provided as the {@link SocialStreamFragment#EXTRA_QUERY} extra in the fragment arguments. If no * search query is provided, the conference hashtag is used as the default query. * * <p>WARNING! This fragment uses the Google+ API, and is subject to quotas. If you expect to * write a wildly popular app based on this code, please check the * at <a href="https://developers.google.com/+/">Google+ Platform documentation</a> on latest * best practices and quota details. You can check your current quota at the * <a href="https://code.google.com/apis/console">APIs console</a>. */ public class SocialStreamFragment extends SherlockListFragment implements AbsListView.OnScrollListener, LoaderManager.LoaderCallbacks<List<Activity>> { private static final String TAG = makeLogTag(SocialStreamFragment.class); public static final String EXTRA_QUERY = "com.google.android.iosched.extra.QUERY"; private static final String STATE_POSITION = "position"; private static final String STATE_TOP = "top"; private static final long MAX_RESULTS_PER_REQUEST = 20; private static final int STREAM_LOADER_ID = 0; private String mSearchString; private List<Activity> mStream = new ArrayList<Activity>(); private StreamAdapter mStreamAdapter = new StreamAdapter(); private int mListViewStatePosition; private int mListViewStateTop; private ImageFetcher mImageFetcher; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments()); // mSearchString can be populated before onCreate() by called refresh(String) if (TextUtils.isEmpty(mSearchString)) { mSearchString = intent.getStringExtra(EXTRA_QUERY); } if (TextUtils.isEmpty(mSearchString)) { mSearchString = UIUtils.CONFERENCE_HASHTAG; } if (!mSearchString.startsWith("#")) { mSearchString = "#" + mSearchString; } mImageFetcher = UIUtils.getImageFetcher(getActivity()); setListAdapter(mStreamAdapter); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (savedInstanceState != null) { mListViewStatePosition = savedInstanceState.getInt(STATE_POSITION, -1); mListViewStateTop = savedInstanceState.getInt(STATE_TOP, 0); } else { mListViewStatePosition = -1; mListViewStateTop = 0; } return super.onCreateView(inflater, container, savedInstanceState); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setEmptyText(getString(R.string.empty_social_stream)); // In support library r8, calling initLoader for a fragment in a FragmentPagerAdapter // in the fragment's onCreate may cause the same LoaderManager to be dealt to multiple // fragments because their mIndex is -1 (haven't been added to the activity yet). Thus, // we do this in onActivityCreated. getLoaderManager().initLoader(STREAM_LOADER_ID, null, this); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); view.setBackgroundColor(Color.WHITE); final ListView listView = getListView(); listView.setCacheColorHint(Color.WHITE); listView.setOnScrollListener(this); listView.setDrawSelectorOnTop(true); TypedValue v = new TypedValue(); getActivity().getTheme().resolveAttribute(R.attr.activatableItemBackground, v, true); listView.setSelector(v.resourceId); } @Override public void onPause() { super.onPause(); mImageFetcher.setPauseWork(false); mImageFetcher.flushCache(); } @Override public void onDestroy() { super.onDestroy(); mImageFetcher.closeCache(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.social_stream, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_compose: Intent intent = ShareCompat.IntentBuilder.from(getActivity()) .setType("text/plain") .setText(mSearchString + "\n\n") .getIntent(); UIUtils.preferPackageForIntent(getActivity(), intent, UIUtils.GOOGLE_PLUS_PACKAGE_NAME); startActivity(intent); EasyTracker.getTracker().trackEvent("Home Screen Dashboard", "Click", "Post to Google+", 0L); LOGD("Tracker", "Home Screen Dashboard: Click, post to Google+"); return true; } return super.onOptionsItemSelected(item); } @Override public void onSaveInstanceState(Bundle outState) { if (isAdded()) { View v = getListView().getChildAt(0); int top = (v == null) ? 0 : v.getTop(); outState.putInt(STATE_POSITION, getListView().getFirstVisiblePosition()); outState.putInt(STATE_TOP, top); } super.onSaveInstanceState(outState); } public void refresh(String newQuery) { mSearchString = newQuery; refresh(true); } public void refresh() { refresh(false); } public void refresh(boolean forceRefresh) { if (isStreamLoading() && !forceRefresh) { return; } // clear current items mStream.clear(); mStreamAdapter.notifyDataSetInvalidated(); if (isAdded()) { Loader loader = getLoaderManager().getLoader(STREAM_LOADER_ID); ((StreamLoader) loader).init(mSearchString); } loadMoreResults(); } public void loadMoreResults() { if (isAdded()) { Loader loader = getLoaderManager().getLoader(STREAM_LOADER_ID); if (loader != null) { loader.forceLoad(); } } } @Override public void onListItemClick(ListView l, View v, int position, long id) { Activity activity = mStream.get(position); Intent postDetailIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(activity.getUrl())); postDetailIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); UIUtils.preferPackageForIntent(getActivity(), postDetailIntent, UIUtils.GOOGLE_PLUS_PACKAGE_NAME); UIUtils.safeOpenLink(getActivity(), postDetailIntent); } @Override public void onScrollStateChanged(AbsListView listView, int scrollState) { // Pause disk cache access to ensure smoother scrolling if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING || scrollState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) { mImageFetcher.setPauseWork(true); } else { mImageFetcher.setPauseWork(false); } } @Override public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { // Simple implementation of the infinite scrolling UI pattern; loads more Google+ // search results as the user scrolls to the end of the list. if (!isStreamLoading() && streamHasMoreResults() && visibleItemCount != 0 && firstVisibleItem + visibleItemCount >= totalItemCount - 1) { loadMoreResults(); } } @Override public Loader<List<Activity>> onCreateLoader(int id, Bundle args) { return new StreamLoader(getActivity(), mSearchString); } @Override public void onLoadFinished(Loader<List<Activity>> listLoader, List<Activity> activities) { if (activities != null) { mStream = activities; } mStreamAdapter.notifyDataSetChanged(); if (mListViewStatePosition != -1 && isAdded()) { getListView().setSelectionFromTop(mListViewStatePosition, mListViewStateTop); mListViewStatePosition = -1; } } @Override public void onLoaderReset(Loader<List<Activity>> listLoader) { } private boolean isStreamLoading() { if (isAdded()) { final Loader loader = getLoaderManager().getLoader(STREAM_LOADER_ID); if (loader != null) { return ((StreamLoader) loader).isLoading(); } } return true; } private boolean streamHasMoreResults() { if (isAdded()) { final Loader loader = getLoaderManager().getLoader(STREAM_LOADER_ID); if (loader != null) { return ((StreamLoader) loader).hasMoreResults(); } } return false; } private boolean streamHasError() { if (isAdded()) { final Loader loader = getLoaderManager().getLoader(STREAM_LOADER_ID); if (loader != null) { return ((StreamLoader) loader).hasError(); } } return false; } /** * An {@link AsyncTaskLoader} that loads activities from the public Google+ stream for * a given search query. The loader maintains a page state with the Google+ API and thus * supports pagination. */ private static class StreamLoader extends AsyncTaskLoader<List<Activity>> { List<Activity> mActivities; private String mSearchString; private String mNextPageToken; private boolean mIsLoading; private boolean mHasError; public StreamLoader(Context context, String searchString) { super(context); init(searchString); } private void init(String searchString) { mSearchString = searchString; mHasError = false; mNextPageToken = null; mIsLoading = true; mActivities = null; } @Override public List<Activity> loadInBackground() { mIsLoading = true; // Set up the HTTP transport and JSON factory HttpTransport httpTransport = new NetHttpTransport(); JsonFactory jsonFactory = new JacksonFactory(); JsonHttpRequestInitializer initializer = new GoogleKeyInitializer( Config.API_KEY); // Set up the main Google+ class Plus plus = Plus.builder(httpTransport, jsonFactory) .setApplicationName(Config.APP_NAME) .setJsonHttpRequestInitializer(initializer) .build(); ActivityFeed activities = null; try { activities = plus.activities().search(mSearchString) .setPageToken(mNextPageToken) .setMaxResults(MAX_RESULTS_PER_REQUEST) .execute(); mHasError = false; mNextPageToken = activities.getNextPageToken(); } catch (IOException e) { e.printStackTrace(); mHasError = true; mNextPageToken = null; } return (activities != null) ? activities.getItems() : null; } @Override public void deliverResult(List<Activity> activities) { mIsLoading = false; if (activities != null) { if (mActivities == null) { mActivities = activities; } else { mActivities.addAll(activities); } } if (isStarted()) { // Need to return new ArrayList for some reason or onLoadFinished() is not called super.deliverResult(mActivities == null ? null : new ArrayList<Activity>(mActivities)); } } @Override protected void onStartLoading() { if (mActivities != null) { // If we already have results and are starting up, deliver what we already have. deliverResult(null); } else { forceLoad(); } } @Override protected void onStopLoading() { mIsLoading = false; cancelLoad(); } @Override protected void onReset() { super.onReset(); onStopLoading(); mActivities = null; } public boolean isLoading() { return mIsLoading; } public boolean hasMoreResults() { return mNextPageToken != null; } public boolean hasError() { return mHasError; } public void setSearchString(String searchString) { mSearchString = searchString; } public void refresh(String searchString) { setSearchString(searchString); refresh(); } public void refresh() { reset(); startLoading(); } } /** * A list adapter that shows individual Google+ activities as list items. * If another page is available, the last item is a "loading" view to support the * infinite scrolling UI pattern. */ private class StreamAdapter extends BaseAdapter { private static final int VIEW_TYPE_ACTIVITY = 0; private static final int VIEW_TYPE_LOADING = 1; @Override public boolean areAllItemsEnabled() { return false; } @Override public boolean isEnabled(int position) { return getItemViewType(position) == VIEW_TYPE_ACTIVITY; } @Override public int getViewTypeCount() { return 2; } @Override public boolean hasStableIds() { return true; } @Override public int getCount() { return mStream.size() + ( // show the status list row if... ((isStreamLoading() && mStream.size() == 0) // ...this is the first load || streamHasMoreResults() // ...or there's another page || streamHasError()) // ...or there's an error ? 1 : 0); } @Override public int getItemViewType(int position) { return (position >= mStream.size()) ? VIEW_TYPE_LOADING : VIEW_TYPE_ACTIVITY; } @Override public Object getItem(int position) { return (getItemViewType(position) == VIEW_TYPE_ACTIVITY) ? mStream.get(position) : null; } @Override public long getItemId(int position) { // TODO: better unique ID heuristic return (getItemViewType(position) == VIEW_TYPE_ACTIVITY) ? mStream.get(position).getId().hashCode() : -1; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (getItemViewType(position) == VIEW_TYPE_LOADING) { if (convertView == null) { convertView = getLayoutInflater(null).inflate( R.layout.list_item_stream_status, parent, false); } if (streamHasError()) { convertView.findViewById(android.R.id.progress).setVisibility(View.GONE); ((TextView) convertView.findViewById(android.R.id.text1)).setText( R.string.stream_error); } else { convertView.findViewById(android.R.id.progress).setVisibility(View.VISIBLE); ((TextView) convertView.findViewById(android.R.id.text1)).setText( R.string.loading); } return convertView; } else { Activity activity = (Activity) getItem(position); if (convertView == null) { convertView = getLayoutInflater(null).inflate( R.layout.list_item_stream_activity, parent, false); } StreamRowViewBinder.bindActivityView(convertView, activity, mImageFetcher); return convertView; } } } /** * A helper class to bind data from a Google+ {@link Activity} to the list item view. */ private static class StreamRowViewBinder { private static class ViewHolder { private TextView[] detail; private ImageView[] detailIcon; private ImageView[] media; private ImageView[] mediaOverlay; private TextView originalAuthor; private View reshareLine; private View reshareSpacer; private ImageView userImage; private TextView userName; private TextView content; private View plusOneIcon; private TextView plusOneCount; private View commentIcon; private TextView commentCount; } private static void bindActivityView( final View rootView, Activity activity, ImageFetcher imageFetcher) { // Prepare view holder. ViewHolder temp = (ViewHolder) rootView.getTag(); final ViewHolder views; if (temp != null) { views = temp; } else { views = new ViewHolder(); rootView.setTag(views); views.detail = new TextView[] { (TextView) rootView.findViewById(R.id.stream_detail_text) }; views.detailIcon = new ImageView[] { (ImageView) rootView.findViewById(R.id.stream_detail_media_small) }; views.media = new ImageView[] { (ImageView) rootView.findViewById(R.id.stream_media_1_1), (ImageView) rootView.findViewById(R.id.stream_media_1_2), }; views.mediaOverlay = new ImageView[] { (ImageView) rootView.findViewById(R.id.stream_media_overlay_1_1), (ImageView) rootView.findViewById(R.id.stream_media_overlay_1_2), }; views.originalAuthor = (TextView) rootView.findViewById(R.id.stream_original_author); views.reshareLine = rootView.findViewById(R.id.stream_reshare_line); views.reshareSpacer = rootView.findViewById(R.id.stream_reshare_spacer); views.userImage = (ImageView) rootView.findViewById(R.id.stream_user_image); views.userName = (TextView) rootView.findViewById(R.id.stream_user_name); views.content = (TextView) rootView.findViewById(R.id.stream_content); views.plusOneIcon = rootView.findViewById(R.id.stream_plus_one_icon); views.plusOneCount = (TextView) rootView.findViewById(R.id.stream_plus_one_count); views.commentIcon = rootView.findViewById(R.id.stream_comment_icon); views.commentCount = (TextView) rootView.findViewById(R.id.stream_comment_count); } final Resources res = rootView.getContext().getResources(); // Hide all the array items. int detailIndex = 0; int mediaIndex = 0; for (View v : views.detail) { v.setVisibility(View.GONE); } for (View v : views.detailIcon) { v.setVisibility(View.GONE); } for (View v : views.media) { v.setVisibility(View.GONE); } for (View v : views.mediaOverlay) { v.setVisibility(View.GONE); } // Determine if this is a reshare (affects how activity fields are to be // interpreted). boolean isReshare = (activity.getObject().getActor() != null); // Set user name. views.userName.setText(activity.getActor().getDisplayName()); if (activity.getActor().getImage() != null) { imageFetcher.loadThumbnailImage(activity.getActor().getImage().getUrl(), views.userImage, R.drawable.person_image_empty); } else { views.userImage.setImageResource(R.drawable.person_image_empty); } // Set +1 and comment counts. final int plusOneCount = (activity.getObject().getPlusoners() != null) ? activity.getObject().getPlusoners().getTotalItems().intValue() : 0; if (plusOneCount == 0) { views.plusOneIcon.setVisibility(View.GONE); views.plusOneCount.setVisibility(View.GONE); } else { views.plusOneIcon.setVisibility(View.VISIBLE); views.plusOneCount.setVisibility(View.VISIBLE); views.plusOneCount.setText(Integer.toString(plusOneCount)); } final int commentCount = (activity.getObject().getReplies() != null) ? activity.getObject().getReplies().getTotalItems().intValue() : 0; if (commentCount == 0) { views.commentIcon.setVisibility(View.GONE); views.commentCount.setVisibility(View.GONE); } else { views.commentIcon.setVisibility(View.VISIBLE); views.commentCount.setVisibility(View.VISIBLE); views.commentCount.setText(Integer.toString(commentCount)); } // Set content. String selfContent = isReshare ? activity.getAnnotation() : activity.getObject().getContent(); if (!TextUtils.isEmpty(selfContent)) { views.content.setVisibility(View.VISIBLE); views.content.setText(Html.fromHtml(selfContent)); } else { views.content.setVisibility(View.GONE); } // Set original author. if (activity.getObject().getActor() != null) { views.originalAuthor.setVisibility(View.VISIBLE); views.originalAuthor.setText(res.getString(R.string.stream_originally_shared, activity.getObject().getActor().getDisplayName())); views.reshareLine.setVisibility(View.VISIBLE); views.reshareSpacer.setVisibility(View.INVISIBLE); } else { views.originalAuthor.setVisibility(View.GONE); views.reshareLine.setVisibility(View.GONE); views.reshareSpacer.setVisibility(View.GONE); } // Set document content. if (isReshare && !TextUtils.isEmpty(activity.getObject().getContent()) && detailIndex < views.detail.length) { views.detail[detailIndex].setVisibility(View.VISIBLE); views.detail[detailIndex].setTextColor(res.getColor(R.color.stream_content_color)); views.detail[detailIndex].setText(Html.fromHtml(activity.getObject().getContent())); ++detailIndex; } // Set location. String location = activity.getPlaceName(); if (!TextUtils.isEmpty(location)) { location = activity.getAddress(); } if (!TextUtils.isEmpty(location)) { location = activity.getGeocode(); } if (!TextUtils.isEmpty(location) && detailIndex < views.detail.length) { views.detail[detailIndex].setVisibility(View.VISIBLE); views.detail[detailIndex].setTextColor(res.getColor(R.color.stream_link_color)); views.detailIcon[detailIndex].setVisibility(View.VISIBLE); views.detail[detailIndex].setText(location); if ("checkin".equals(activity.getVerb())) { views.detailIcon[detailIndex].setImageResource(R.drawable.stream_ic_checkin); } else { views.detailIcon[detailIndex].setImageResource(R.drawable.stream_ic_location); } ++detailIndex; } // Set media content. if (activity.getObject().getAttachments() != null) { for (Activity.PlusObject.Attachments attachment : activity.getObject().getAttachments()) { String objectType = attachment.getObjectType(); if (("photo".equals(objectType) || "video".equals(objectType)) && mediaIndex < views.media.length) { if (attachment.getImage() == null) { continue; } final ImageView mediaView = views.media[mediaIndex]; mediaView.setVisibility(View.VISIBLE); imageFetcher.loadThumbnailImage(attachment.getImage().getUrl(), mediaView); if ("video".equals(objectType)) { views.mediaOverlay[mediaIndex].setVisibility(View.VISIBLE); } ++mediaIndex; } else if (("article".equals(objectType)) && detailIndex < views.detail.length) { try { String faviconUrl = "http://www.google.com/s2/favicons?domain=" + Uri.parse(attachment.getUrl()).getHost(); final ImageView iconView = views.detailIcon[detailIndex]; iconView.setVisibility(View.VISIBLE); imageFetcher.loadThumbnailImage(faviconUrl, iconView); } catch (ParseException ignored) {} views.detail[detailIndex].setVisibility(View.VISIBLE); views.detail[detailIndex].setTextColor( res.getColor(R.color.stream_link_color)); views.detail[detailIndex].setText(attachment.getDisplayName()); ++detailIndex; } } } } } }
1162584980-google-io
android/src/com/google/android/apps/iosched/ui/SocialStreamFragment.java
Java
asf20
29,610
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import android.os.Bundle; import android.support.v4.app.Fragment; /** * A single-pane activity that shows a {@link SocialStreamFragment}. */ public class SocialStreamActivity extends SimpleSinglePaneActivity { @Override protected Fragment onCreatePane() { return new SocialStreamFragment(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); setTitle(getIntent().getStringExtra(SocialStreamFragment.EXTRA_QUERY)); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getSupportMenuInflater().inflate(R.menu.social_stream_standalone, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_refresh: ((SocialStreamFragment) getFragment()).refresh(); return true; } return super.onOptionsItemSelected(item); } }
1162584980-google-io
android/src/com/google/android/apps/iosched/ui/SocialStreamActivity.java
Java
asf20
1,820
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.util.AccountUtils; import com.google.android.apps.iosched.util.BeamUtils; import com.google.android.apps.iosched.util.UIUtils; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.view.MenuItem; import android.annotation.TargetApi; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.nfc.NfcAdapter; import android.nfc.NfcEvent; import android.os.Build; import android.os.Bundle; import android.support.v4.app.NavUtils; /** * A base activity that handles common functionality in the app. */ public abstract class BaseActivity extends SherlockFragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); EasyTracker.getTracker().setContext(this); // If we're not on Google TV and we're not authenticated, finish this activity // and show the authentication screen. if (!UIUtils.isGoogleTV(this)) { if (!AccountUtils.isAuthenticated(this)) { AccountUtils.startAuthenticationFlow(this, getIntent()); finish(); } } // If Android Beam APIs are available, set up the Beam easter egg as the default Beam // content. This can be overridden by subclasses. if (UIUtils.hasICS()) { BeamUtils.setDefaultBeamUri(this); if (!BeamUtils.isBeamUnlocked(this)) { BeamUtils.setBeamCompleteCallback(this, new NfcAdapter.OnNdefPushCompleteCallback() { @Override @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public void onNdefPushComplete(NfcEvent event) { onBeamSent(); } }); } } getSupportActionBar().setHomeButtonEnabled(true); } private void onBeamSent() { if (!BeamUtils.isBeamUnlocked(this)) { BeamUtils.setBeamUnlocked(this); runOnUiThread(new Runnable() { @Override public void run() { new AlertDialog.Builder(BaseActivity.this) .setTitle(R.string.just_beamed) .setMessage(R.string.beam_unlocked_default) .setNegativeButton(R.string.close, null) .setPositiveButton(R.string.view_beam_session, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { BeamUtils.launchBeamSession(BaseActivity.this); di.dismiss(); } }) .create() .show(); } }); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: if (this instanceof HomeActivity) { return false; } NavUtils.navigateUpFromSameTask(this); return true; } return super.onOptionsItemSelected(item); } /** * Sets the icon color using some fancy blending mode trickery. */ protected void setActionBarColor(int color) { if (color == 0) { color = 0xffffffff; } final Resources res = getResources(); Drawable maskDrawable = res.getDrawable(R.drawable.actionbar_icon_mask); if (!(maskDrawable instanceof BitmapDrawable)) { return; } Bitmap maskBitmap = ((BitmapDrawable) maskDrawable).getBitmap(); final int width = maskBitmap.getWidth(); final int height = maskBitmap.getHeight(); Bitmap outBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(outBitmap); canvas.drawBitmap(maskBitmap, 0, 0, null); Paint maskedPaint = new Paint(); maskedPaint.setColor(color); maskedPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP)); canvas.drawRect(0, 0, width, height, maskedPaint); BitmapDrawable outDrawable = new BitmapDrawable(res, outBitmap); getSupportActionBar().setIcon(outDrawable); } /** * Converts an intent into a {@link Bundle} suitable for use as fragment arguments. */ public static Bundle intentToFragmentArguments(Intent intent) { Bundle arguments = new Bundle(); if (intent == null) { return arguments; } final Uri data = intent.getData(); if (data != null) { arguments.putParcelable("_uri", data); } final Bundle extras = intent.getExtras(); if (extras != null) { arguments.putAll(intent.getExtras()); } return arguments; } /** * Converts a fragment arguments bundle into an intent. */ public static Intent fragmentArgumentsToIntent(Bundle arguments) { Intent intent = new Intent(); if (arguments == null) { return intent; } final Uri data = arguments.getParcelable("_uri"); if (data != null) { intent.setData(data); } intent.putExtras(arguments); intent.removeExtra("_uri"); return intent; } @Override protected void onStart() { super.onStart(); EasyTracker.getTracker().trackActivityStart(this); } @Override protected void onStop() { super.onStop(); EasyTracker.getTracker().trackActivityStop(this); } }
1162584980-google-io
android/src/com/google/android/apps/iosched/ui/BaseActivity.java
Java
asf20
7,118
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.graphics.drawable.ColorDrawable; import android.provider.BaseColumns; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.ImageView; import android.widget.TextView; /** * A {@link android.widget.CursorAdapter} that renders a {@link TracksQuery}, additionally showing * "Map" and/or "All tracks" list items at the top. */ public class TracksAdapter extends CursorAdapter { private static final int ALL_ITEM_ID = Integer.MAX_VALUE; private static final int MAP_ITEM_ID = Integer.MAX_VALUE - 1; private Activity mActivity; private boolean mHasAllItem; private boolean mHasMapItem; private int mPositionDisplacement; public TracksAdapter(Activity activity) { super(activity, null, false); mActivity = activity; } public void setHasAllItem(boolean hasAllItem) { mHasAllItem = hasAllItem; updatePositionDisplacement(); } public void setHasMapItem(boolean hasMapItem) { mHasMapItem = hasMapItem; updatePositionDisplacement(); } private void updatePositionDisplacement() { mPositionDisplacement = (mHasAllItem ? 1 : 0) + (mHasMapItem ? 1 : 0); } public boolean isMapItem(int position) { return mHasMapItem && position == 0; } public boolean isAllItem(int position) { return mHasAllItem && position == (mHasMapItem ? 1 : 0); } @Override public int getCount() { return super.getCount() + mPositionDisplacement; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (isMapItem(position)) { if (convertView == null) { convertView = mActivity.getLayoutInflater().inflate( R.layout.list_item_track_map, parent, false); } return convertView; } else if (isAllItem(position)) { if (convertView == null) { convertView = mActivity.getLayoutInflater().inflate( R.layout.list_item_track, parent, false); } // Custom binding for the first item ((TextView) convertView.findViewById(android.R.id.text1)).setText( "(" + mActivity.getResources().getString(R.string.all_tracks) + ")"); convertView.findViewById(android.R.id.icon1).setVisibility(View.INVISIBLE); return convertView; } return super.getView(position - mPositionDisplacement, convertView, parent); } @Override public Object getItem(int position) { if (isMapItem(position) || isAllItem(position)) { return null; } return super.getItem(position - mPositionDisplacement); } @Override public long getItemId(int position) { if (isMapItem(position)) { return MAP_ITEM_ID; } else if (isAllItem(position)) { return ALL_ITEM_ID; } return super.getItemId(position - mPositionDisplacement); } @Override public boolean isEnabled(int position) { return (mHasAllItem && position == 0) || super.isEnabled(position - mPositionDisplacement); } @Override public int getViewTypeCount() { // Add an item type for the "All" and map views. return super.getViewTypeCount() + 2; } @Override public int getItemViewType(int position) { if (isMapItem(position)) { return getViewTypeCount() - 1; } else if (isAllItem(position)) { return getViewTypeCount() - 2; } return super.getItemViewType(position - mPositionDisplacement); } /** {@inheritDoc} */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return mActivity.getLayoutInflater().inflate(R.layout.list_item_track, parent, false); } /** {@inheritDoc} */ @Override public void bindView(View view, Context context, Cursor cursor) { final TextView textView = (TextView) view.findViewById(android.R.id.text1); textView.setText(cursor.getString(TracksQuery.TRACK_NAME)); // Assign track color to visible block final ImageView iconView = (ImageView) view.findViewById(android.R.id.icon1); iconView.setImageDrawable(new ColorDrawable(cursor.getInt(TracksQuery.TRACK_COLOR))); } /** {@link com.google.android.apps.iosched.provider.ScheduleContract.Tracks} query parameters. */ public interface TracksQuery { int _TOKEN = 0x1; String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Tracks.TRACK_ID, ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Tracks.TRACK_ABSTRACT, ScheduleContract.Tracks.TRACK_COLOR, }; String[] PROJECTION_WITH_SESSIONS_COUNT = { BaseColumns._ID, ScheduleContract.Tracks.TRACK_ID, ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Tracks.TRACK_ABSTRACT, ScheduleContract.Tracks.TRACK_COLOR, ScheduleContract.Tracks.SESSIONS_COUNT, }; String[] PROJECTION_WITH_VENDORS_COUNT = { BaseColumns._ID, ScheduleContract.Tracks.TRACK_ID, ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Tracks.TRACK_ABSTRACT, ScheduleContract.Tracks.TRACK_COLOR, ScheduleContract.Tracks.VENDORS_COUNT, }; int _ID = 0; int TRACK_ID = 1; int TRACK_NAME = 2; int TRACK_ABSTRACT = 3; int TRACK_COLOR = 4; } }
1162584980-google-io
android/src/com/google/android/apps/iosched/ui/TracksAdapter.java
Java
asf20
6,615
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.gtv; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.Config; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.sync.SyncHelper; import com.google.android.apps.iosched.ui.BaseActivity; import com.google.android.apps.iosched.ui.SessionLivestreamActivity.SessionSummaryFragment; import com.google.android.apps.iosched.util.UIUtils; import com.google.android.youtube.api.YouTube; import com.google.android.youtube.api.YouTubePlayer; import android.annotation.TargetApi; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.provider.BaseColumns; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.widget.CursorAdapter; import android.text.TextUtils; import android.text.format.DateUtils; import android.text.method.LinkMovementMethod; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.io.IOException; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.LOGE; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * A Google TV home activity for Google I/O 2012 that displays session live streams pulled in * from YouTube. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class GoogleTVSessionLivestreamActivity extends BaseActivity implements LoaderCallbacks<Cursor>, YouTubePlayer.OnPlaybackEventsListener, YouTubePlayer.OnFullscreenListener, OnItemClickListener { private static final String TAG = makeLogTag(GoogleTVSessionLivestreamActivity.class); private static final String TAG_SESSION_SUMMARY = "session_summary"; private static final int UPCOMING_SESSIONS_QUERY_ID = 3; private static final String PROMO_VIDEO_URL = "http://www.youtube.com/watch?v=gTA-5HM8Zhs"; private boolean mIsFullscreen = false; private boolean mTrackPlay = true; private YouTubePlayer mYouTubePlayer; private FrameLayout mPlayerContainer; private String mYouTubeVideoId; private LinearLayout mMainLayout; private LinearLayout mVideoLayout; private LinearLayout mExtraLayout; private FrameLayout mSummaryLayout; private ListView mLiveListView; private SyncHelper mGTVSyncHelper; private LivestreamAdapter mLivestreamAdapter; private String mSessionId; private Handler mHandler = new Handler(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); YouTube.initialize(this, Config.YOUTUBE_API_KEY); setContentView(R.layout.activity_session_livestream); // Set up YouTube player mYouTubePlayer = (YouTubePlayer) getSupportFragmentManager().findFragmentById( R.id.livestream_player); mYouTubePlayer.setOnPlaybackEventsListener(this); mYouTubePlayer.enableCustomFullscreen(this); mYouTubePlayer.setFullscreenControlFlags( YouTubePlayer.FULLSCREEN_FLAG_CONTROL_SYSTEM_UI); // Views that are common over all layouts mMainLayout = (LinearLayout) findViewById(R.id.livestream_mainlayout); mPlayerContainer = (FrameLayout) findViewById(R.id.livestream_player_container); // Tablet UI specific views getSupportFragmentManager().beginTransaction().add(R.id.livestream_summary, new SessionSummaryFragment(), TAG_SESSION_SUMMARY).commit(); mVideoLayout = (LinearLayout) findViewById(R.id.livestream_videolayout); mExtraLayout = (LinearLayout) findViewById(R.id.googletv_livesextra_layout); mSummaryLayout = (FrameLayout) findViewById(R.id.livestream_summary); // Reload all other data in this activity reloadFromUri(getIntent().getData()); // Start sessions query to populate action bar navigation spinner getSupportLoaderManager().initLoader(SessionsQuery._TOKEN, null, this); // Set up left side listview mLivestreamAdapter = new LivestreamAdapter(this); mLiveListView = (ListView) findViewById(R.id.live_session_list); mLiveListView.setAdapter(mLivestreamAdapter); mLiveListView.setOnItemClickListener(this); mLiveListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); mLiveListView.setSelector(android.R.color.transparent); getSupportActionBar().hide(); // Sync data from Conference API new SyncOperationTask().execute((Void) null); } /** * Reloads all data in the activity and fragments from a given uri */ private void reloadFromUri(Uri newUri) { if (newUri != null && newUri.getPathSegments().size() >= 2) { mSessionId = Sessions.getSessionId(newUri); getSupportLoaderManager().restartLoader(SessionSummaryQuery._TOKEN, null, this); } } @Override public void onBackPressed() { if (mIsFullscreen) { // Exit full screen mode on back key mYouTubePlayer.setFullscreen(false); } else { super.onBackPressed(); } } @Override public void onItemClick(AdapterView<?> adapterView, View view, int itemPosition, long itemId) { final Cursor cursor = (Cursor) mLivestreamAdapter.getItem(itemPosition); final String sessionId = cursor.getString(SessionsQuery.SESSION_ID); if (sessionId != null) { reloadFromUri(Sessions.buildSessionUri(sessionId)); } } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { switch (id) { case SessionSummaryQuery._TOKEN: return new CursorLoader( this, Sessions.buildWithTracksUri(mSessionId), SessionSummaryQuery.PROJECTION, null, null, null); case SessionsQuery._TOKEN: final long currentTime = UIUtils.getCurrentTime(this); String selection = Sessions.LIVESTREAM_SELECTION + " and " + Sessions.AT_TIME_SELECTION; String[] selectionArgs = Sessions.buildAtTimeSelectionArgs(currentTime); return new CursorLoader(this, Sessions.buildWithTracksUri(), SessionsQuery.PROJECTION, selection, selectionArgs, null); case UPCOMING_SESSIONS_QUERY_ID: final long newCurrentTime = UIUtils.getCurrentTime(this); String sessionsSelection = Sessions.LIVESTREAM_SELECTION + " and " + Sessions.UPCOMING_SELECTION; String[] sessionsSelectionArgs = Sessions.buildUpcomingSelectionArgs(newCurrentTime); return new CursorLoader(this, Sessions.buildWithTracksUri(), SessionsQuery.PROJECTION, sessionsSelection, sessionsSelectionArgs, null); } return null; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { mHandler.removeCallbacks(mNextSessionStartsInCountdownRunnable); switch (loader.getId()) { case SessionSummaryQuery._TOKEN: loadSession(data); break; case SessionsQuery._TOKEN: mLivestreamAdapter.swapCursor(data); final int selected = locateSelectedItem(data); if (data.getCount() == 0) { handleNoLiveSessionsAvailable(); } else { mLiveListView.setSelection(selected); mLiveListView.requestFocus(selected); final Cursor cursor = (Cursor) mLivestreamAdapter.getItem(selected); final String sessionId = cursor.getString(SessionsQuery.SESSION_ID); if (sessionId != null) { reloadFromUri(Sessions.buildSessionUri(sessionId)); } } break; case UPCOMING_SESSIONS_QUERY_ID: if (data != null && data.getCount() > 0) { data.moveToFirst(); handleUpdateNextUpcomingSession(data); } break; } } public void handleNoLiveSessionsAvailable() { getSupportLoaderManager().initLoader(UPCOMING_SESSIONS_QUERY_ID, null, this); updateSessionViews(PROMO_VIDEO_URL, getString(R.string.missed_io_title), getString(R.string.missed_io_subtitle), UIUtils.CONFERENCE_HASHTAG); //Make link in abstract view clickable TextView abstractLinkTextView = (TextView) findViewById(R.id.session_abstract); abstractLinkTextView.setMovementMethod(new LinkMovementMethod()); } private String mNextSessionTitle; private long mNextSessionStartTime; private final Runnable mNextSessionStartsInCountdownRunnable = new Runnable() { public void run() { int remainingSec = (int) Math.max(0, (mNextSessionStartTime - UIUtils.getCurrentTime( GoogleTVSessionLivestreamActivity.this)) / 1000); final int secs = remainingSec % 86400; final int days = remainingSec / 86400; final String str; if (days == 0) { str = getResources().getString( R.string.starts_in_template_0_days, DateUtils.formatElapsedTime(secs)); } else { str = getResources().getQuantityString( R.plurals.starts_in_template, days, days, DateUtils.formatElapsedTime(secs)); } updateSessionSummaryFragment(mNextSessionTitle, str); if (remainingSec == 0) { // Next session starting now! mHandler.postDelayed(mRefreshSessionsRunnable, 1000); return; } // Repost ourselves to keep updating countdown mHandler.postDelayed(mNextSessionStartsInCountdownRunnable, 1000); } }; private final Runnable mRefreshSessionsRunnable = new Runnable() { @Override public void run() { getSupportLoaderManager().restartLoader(SessionsQuery._TOKEN, null, GoogleTVSessionLivestreamActivity.this); } }; public void handleUpdateNextUpcomingSession(Cursor data) { mNextSessionTitle = getString(R.string.next_live_stream_session_template, data.getString(SessionsQuery.TITLE)); mNextSessionStartTime = data.getLong(SessionsQuery.BLOCK_START); updateSessionViews(PROMO_VIDEO_URL, mNextSessionTitle, "", UIUtils.CONFERENCE_HASHTAG); // Begin countdown til next session mHandler.post(mNextSessionStartsInCountdownRunnable); } /** * Locates which item should be selected in the action bar drop-down spinner based on the * current active session uri */ private int locateSelectedItem(Cursor data) { int selected = 0; if (data != null && mSessionId != null) { while (data.moveToNext()) { if (mSessionId.equals(data.getString(SessionsQuery.SESSION_ID))) { selected = data.getPosition(); } } } return selected; } @Override public void onLoaderReset(Loader<Cursor> loader) { switch (loader.getId()) { case SessionsQuery._TOKEN: mLivestreamAdapter.swapCursor(null); break; } } @Override public void onFullscreen(boolean fullScreen) { layoutFullscreenVideo(fullScreen); } @Override public void onLoaded(String s) { } @Override public void onPlaying() { } @Override public void onPaused() { } @Override public void onBuffering(boolean b) { } @Override public void onEnded() { mHandler.post(mRefreshSessionsRunnable); } @Override public void onError() { Toast.makeText(this, R.string.session_livestream_error, Toast.LENGTH_LONG).show(); LOGE(TAG, getString(R.string.session_livestream_error)); } private void loadSession(Cursor data) { if (data != null && data.moveToFirst()) { // Schedule a data refresh after the session ends. // NOTE: using postDelayed instead of postAtTime helps during debugging, using // mock times. mHandler.postDelayed(mRefreshSessionsRunnable, data.getLong(SessionSummaryQuery.BLOCK_END) + 1000 - UIUtils.getCurrentTime(this)); updateSessionViews( data.getString(SessionSummaryQuery.LIVESTREAM_URL), data.getString(SessionSummaryQuery.TITLE), data.getString(SessionSummaryQuery.ABSTRACT), data.getString(SessionSummaryQuery.HASHTAGS)); } } /** * Updates views that rely on session data from explicit strings. */ private void updateSessionViews(final String youtubeUrl, final String title, final String sessionAbstract, final String hashTag) { if (youtubeUrl == null) { // Get out, nothing to do here Toast.makeText(this, R.string.error_tv_no_url, Toast.LENGTH_SHORT).show(); LOGE(TAG, getString(R.string.error_tv_no_url)); return; } String youtubeVideoId = youtubeUrl; if (youtubeUrl.startsWith("http")) { final Uri youTubeUri = Uri.parse(youtubeUrl); youtubeVideoId = youTubeUri.getQueryParameter("v"); } playVideo(youtubeVideoId); if (mTrackPlay) { EasyTracker.getTracker().trackView("Live Streaming: " + title); LOGD("Tracker", "Live Streaming: " + title); } updateSessionSummaryFragment(title, sessionAbstract); mLiveListView.requestFocus(); } private void updateSessionSummaryFragment(String title, String sessionAbstract) { SessionSummaryFragment sessionSummaryFragment = (SessionSummaryFragment) getSupportFragmentManager().findFragmentByTag(TAG_SESSION_SUMMARY); if (sessionSummaryFragment != null) { sessionSummaryFragment.setSessionSummaryInfo(title, sessionAbstract); } } private void playVideo(String videoId) { if ((mYouTubeVideoId == null || !mYouTubeVideoId.equals(videoId)) && !TextUtils.isEmpty(videoId)) { mYouTubeVideoId = videoId; mYouTubePlayer.loadVideo(mYouTubeVideoId); mTrackPlay = true; } else { mTrackPlay = false; } } private void layoutFullscreenVideo(boolean fullscreen) { if (mIsFullscreen != fullscreen) { mIsFullscreen = fullscreen; mYouTubePlayer.setFullscreen(fullscreen); layoutGoogleTVFullScreen(fullscreen); // Full screen layout changes for all form factors final LayoutParams params = (LayoutParams) mPlayerContainer.getLayoutParams(); if (fullscreen) { params.height = LayoutParams.MATCH_PARENT; mMainLayout.setPadding(0, 0, 0, 0); } else { params.height = LayoutParams.WRAP_CONTENT; } mPlayerContainer.setLayoutParams(params); } } /** * Adjusts tablet layouts for full screen video. * * @param fullscreen True to layout in full screen, false to switch to regular layout */ private void layoutGoogleTVFullScreen(boolean fullscreen) { if (fullscreen) { mExtraLayout.setVisibility(View.GONE); mSummaryLayout.setVisibility(View.GONE); mMainLayout.setPadding(0, 0, 0, 0); mVideoLayout.setPadding(0, 0, 0, 0); final LayoutParams videoLayoutParams = (LayoutParams) mVideoLayout.getLayoutParams(); videoLayoutParams.setMargins(0, 0, 0, 0); mVideoLayout.setLayoutParams(videoLayoutParams); } else { final int padding = getResources().getDimensionPixelSize(R.dimen.multipane_half_padding); mExtraLayout.setVisibility(View.VISIBLE); mSummaryLayout.setVisibility(View.VISIBLE); mMainLayout.setPadding(padding, padding, padding, padding); mVideoLayout.setBackgroundResource(R.drawable.grey_frame_on_white); final LayoutParams videoLayoutParams = (LayoutParams) mVideoLayout.getLayoutParams(); videoLayoutParams.setMargins(padding, padding, padding, padding); mVideoLayout.setLayoutParams(videoLayoutParams); } } /** * Adapter that backs the action bar drop-down spinner. */ private class LivestreamAdapter extends CursorAdapter { private LayoutInflater mLayoutInflater; public LivestreamAdapter(Context context) { super(context, null, false); mLayoutInflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE); } @Override public Object getItem(int position) { mCursor.moveToPosition(position); return mCursor; } @Override public View newDropDownView(Context context, Cursor cursor, ViewGroup parent) { // Inflate view that appears in the side list view return mLayoutInflater.inflate( R.layout.list_item_live_session, parent, false); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { // Inflate view that appears in the side list view return mLayoutInflater.inflate(R.layout.list_item_live_session, parent, false); } @Override public void bindView(View view, Context context, Cursor cursor) { final TextView titleView = (TextView) view.findViewById(R.id.live_session_title); final TextView subTitleView = (TextView) view.findViewById(R.id.live_session_subtitle); String trackName = cursor.getString(SessionsQuery.TRACK_NAME); if (TextUtils.isEmpty(trackName)) { trackName = getString(R.string.app_name); } else { trackName = getString(R.string.session_livestream_track_title, trackName); } cursor.getInt(SessionsQuery.TRACK_COLOR); String sessionTitle = cursor.getString(SessionsQuery.TITLE); if (subTitleView != null) { titleView.setText(trackName); subTitleView.setText(sessionTitle); } else { // Selected view titleView.setText(getString(R.string.session_livestream_title) + ": " + trackName); } } } // Enabling media keys for Google TV Devices @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_MEDIA_PAUSE: mYouTubePlayer.pause(); return true; case KeyEvent.KEYCODE_MEDIA_PLAY: mYouTubePlayer.play(); return true; case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD: mYouTubePlayer.seekRelativeMillis(20000); return true; case KeyEvent.KEYCODE_MEDIA_REWIND: mYouTubePlayer.seekRelativeMillis(-20000); return true; default: return super.onKeyDown(keyCode, event); } } // Need to sync with the conference API to get the livestream URLs private class SyncOperationTask extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { // Perform a sync using SyncHelper if (mGTVSyncHelper == null) { mGTVSyncHelper = new SyncHelper(getApplicationContext()); } try { mGTVSyncHelper.performSync(null, SyncHelper.FLAG_SYNC_LOCAL | SyncHelper.FLAG_SYNC_REMOTE); } catch (IOException e) { LOGE(TAG, "Error loading data for Google I/O 2012.", e); } return null; } } /** * Single session query */ public interface SessionSummaryQuery { int _TOKEN = 0; String[] PROJECTION = { ScheduleContract.Sessions.SESSION_ID, ScheduleContract.Sessions.SESSION_TITLE, ScheduleContract.Sessions.SESSION_ABSTRACT, ScheduleContract.Sessions.SESSION_HASHTAGS, ScheduleContract.Sessions.SESSION_LIVESTREAM_URL, ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_END, }; int SESSION_ID = 0; int TITLE = 1; int ABSTRACT = 2; int HASHTAGS = 3; int LIVESTREAM_URL = 4; int TRACK_NAME = 5; int BLOCK_START= 6; int BLOCK_END = 7; } /** * List of sessions query */ public interface SessionsQuery { int _TOKEN = 1; String[] PROJECTION = { BaseColumns._ID, Sessions.SESSION_ID, Sessions.SESSION_TITLE, ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Tracks.TRACK_COLOR, ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_END, }; int ID = 0; int SESSION_ID = 1; int TITLE = 2; int TRACK_NAME = 3; int TRACK_COLOR = 4; int BLOCK_START= 5; int BLOCK_END = 6; } }
1162584980-google-io
android/src/com/google/android/apps/iosched/ui/gtv/GoogleTVSessionLivestreamActivity.java
Java
asf20
23,470
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.widget; import com.google.android.apps.iosched.util.UIUtils; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.LinearLayout; /** * An extremely simple {@link LinearLayout} descendant that simply switches the order of its child * views on Android 4.0+. The reason for this is that on Android, negative buttons should be shown * to the left of positive buttons. */ public class ButtonBar extends LinearLayout { public ButtonBar(Context context) { super(context); } public ButtonBar(Context context, AttributeSet attrs) { super(context, attrs); } public ButtonBar(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public View getChildAt(int index) { if (UIUtils.hasICS()) { // Flip the buttons so that we get e.g. "Cancel | OK" on ICS return super.getChildAt(getChildCount() - 1 - index); } return super.getChildAt(index); } }
1162584980-google-io
android/src/com/google/android/apps/iosched/ui/widget/ButtonBar.java
Java
asf20
1,695
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.widget; import android.animation.Animator; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.util.AttributeSet; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import static com.google.android.apps.iosched.util.LogUtils.LOGW; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * A layout that supports the Show/Hide pattern for portrait tablet layouts. See <a * href="http://developer.android.com/design/patterns/multi-pane-layouts.html#orientation">Android * Design &gt; Patterns &gt; Multi-pane Layouts & gt; Compound Views and Orientation Changes</a> for * more details on this pattern. This layout should normally be used in association with the Up * button. Specifically, show the master pane using {@link #showMaster(boolean, int)} when the Up * button is pressed. If the master pane is visible, defer to normal Up behavior. * * <p>TODO: swiping should be more tactile and actually follow the user's finger. * * <p>Requires API level 11 */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class ShowHideMasterLayout extends ViewGroup implements Animator.AnimatorListener { private static final String TAG = makeLogTag(ShowHideMasterLayout.class); /** * A flag for {@link #showMaster(boolean, int)} indicating that the change in visiblity should * not be animated. */ public static final int FLAG_IMMEDIATE = 0x1; private boolean mFirstShow = true; private boolean mMasterVisible = true; private View mMasterView; private View mDetailView; private OnMasterVisibilityChangedListener mOnMasterVisibilityChangedListener; private GestureDetector mGestureDetector; private boolean mFlingToExposeMaster; private boolean mIsAnimating; private Runnable mShowMasterCompleteRunnable; // The last measured master width, including its margins. private int mTranslateAmount; public interface OnMasterVisibilityChangedListener { public void onMasterVisibilityChanged(boolean visible); } public ShowHideMasterLayout(Context context) { super(context); init(); } public ShowHideMasterLayout(Context context, AttributeSet attrs) { super(context, attrs); init(); } public ShowHideMasterLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } private void init() { mGestureDetector = new GestureDetector(getContext(), mGestureListener); } @Override public LayoutParams generateLayoutParams(AttributeSet attrs) { return new MarginLayoutParams(getContext(), attrs); } @Override protected LayoutParams generateLayoutParams(LayoutParams p) { return new MarginLayoutParams(p); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int count = getChildCount(); // Measure once to find the maximum child size. int maxHeight = 0; int maxWidth = 0; int childState = 0; for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() == GONE) { continue; } measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0); final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); maxWidth = Math.max(maxWidth, child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin); maxHeight = Math.max(maxHeight, child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin); childState = combineMeasuredStates(childState, child.getMeasuredState()); } // Account for padding too maxWidth += getPaddingLeft() + getPaddingRight(); maxHeight += getPaddingLeft() + getPaddingRight(); // Check against our minimum height and width maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight()); maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth()); // Set our own measured size setMeasuredDimension( resolveSizeAndState(maxWidth, widthMeasureSpec, childState), resolveSizeAndState(maxHeight, heightMeasureSpec, childState << MEASURED_HEIGHT_STATE_SHIFT)); // Measure children for them to set their measured dimensions for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() == GONE) { continue; } final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); int childWidthMeasureSpec; int childHeightMeasureSpec; if (lp.width == LayoutParams.MATCH_PARENT) { childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth() - getPaddingLeft() - getPaddingRight() - lp.leftMargin - lp.rightMargin, MeasureSpec.EXACTLY); } else { childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec, getPaddingLeft() + getPaddingRight() + lp.leftMargin + lp.rightMargin, lp.width); } if (lp.height == LayoutParams.MATCH_PARENT) { childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight() - getPaddingTop() - getPaddingBottom() - lp.topMargin - lp.bottomMargin, MeasureSpec.EXACTLY); } else { childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec, getPaddingTop() + getPaddingBottom() + lp.topMargin + lp.bottomMargin, lp.height); } child.measure(childWidthMeasureSpec, childHeightMeasureSpec); } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { updateChildReferences(); if (mMasterView == null || mDetailView == null) { LOGW(TAG, "Master or detail is missing (need 2 children), can't layout."); return; } int masterWidth = mMasterView.getMeasuredWidth(); MarginLayoutParams masterLp = (MarginLayoutParams) mMasterView.getLayoutParams(); MarginLayoutParams detailLp = (MarginLayoutParams) mDetailView.getLayoutParams(); mTranslateAmount = masterWidth + masterLp.leftMargin + masterLp.rightMargin; mMasterView.layout( l + masterLp.leftMargin, t + masterLp.topMargin, l + masterLp.leftMargin + masterWidth, b - masterLp.bottomMargin); mDetailView.layout( l + detailLp.leftMargin + mTranslateAmount, t + detailLp.topMargin, r - detailLp.rightMargin + mTranslateAmount, b - detailLp.bottomMargin); // Update translationX values if (!mIsAnimating) { final float translationX = mMasterVisible ? 0 : -mTranslateAmount; mMasterView.setTranslationX(translationX); mDetailView.setTranslationX(translationX); } } private void updateChildReferences() { int childCount = getChildCount(); mMasterView = (childCount > 0) ? getChildAt(0) : null; mDetailView = (childCount > 1) ? getChildAt(1) : null; } /** * Allow or disallow the user to flick right on the detail pane to expose the master pane. * @param enabled Whether or not to enable this interaction. */ public void setFlingToExposeMasterEnabled(boolean enabled) { mFlingToExposeMaster = enabled; } /** * Request the given listener be notified when the master pane is shown or hidden. * * @param listener The listener to notify when the master pane is shown or hidden. */ public void setOnMasterVisibilityChangedListener(OnMasterVisibilityChangedListener listener) { mOnMasterVisibilityChangedListener = listener; } /** * Returns whether or not the master pane is visible. * * @return True if the master pane is visible. */ public boolean isMasterVisible() { return mMasterVisible; } /** * Calls {@link #showMaster(boolean, int, Runnable)} with a null runnable. */ public void showMaster(boolean show, int flags) { showMaster(show, flags, null); } /** * Shows or hides the master pane. * * @param show Whether or not to show the master pane. * @param flags {@link #FLAG_IMMEDIATE} to show/hide immediately, or 0 to animate. * @param completeRunnable An optional runnable to run when any animations related to this are * complete. */ public void showMaster(boolean show, int flags, Runnable completeRunnable) { if (!mFirstShow && mMasterVisible == show) { return; } mShowMasterCompleteRunnable = completeRunnable; mFirstShow = false; mMasterVisible = show; if (mOnMasterVisibilityChangedListener != null) { mOnMasterVisibilityChangedListener.onMasterVisibilityChanged(show); } updateChildReferences(); if (mMasterView == null || mDetailView == null) { LOGW(TAG, "Master or detail is missing (need 2 children), can't change translation."); return; } final float translationX = show ? 0 : -mTranslateAmount; if ((flags & FLAG_IMMEDIATE) != 0) { mMasterView.setTranslationX(translationX); mDetailView.setTranslationX(translationX); if (mShowMasterCompleteRunnable != null) { mShowMasterCompleteRunnable.run(); mShowMasterCompleteRunnable = null; } } else { final long duration = getResources().getInteger(android.R.integer.config_shortAnimTime); // Animate if we have Honeycomb APIs, don't animate otherwise mIsAnimating = true; AnimatorSet animatorSet = new AnimatorSet(); mMasterView.setLayerType(LAYER_TYPE_HARDWARE, null); mDetailView.setLayerType(LAYER_TYPE_HARDWARE, null); animatorSet .play(ObjectAnimator .ofFloat(mMasterView, "translationX", translationX) .setDuration(duration)) .with(ObjectAnimator .ofFloat(mDetailView, "translationX", translationX) .setDuration(duration)); animatorSet.addListener(this); animatorSet.start(); // For API level 12+, use this instead: // mMasterView.animate().translationX().setDuration(duration); // mDetailView.animate().translationX(show ? masterWidth : 0).setDuration(duration); } } @Override public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { // Really bad hack... we really shouldn't do this. //super.requestDisallowInterceptTouchEvent(disallowIntercept); } @Override public boolean onInterceptTouchEvent(MotionEvent event) { if (mFlingToExposeMaster && !mMasterVisible) { mGestureDetector.onTouchEvent(event); } if (event.getAction() == MotionEvent.ACTION_DOWN && mMasterView != null && mMasterVisible) { // If the master is visible, touching in the detail area should hide the master. if (event.getX() > mTranslateAmount) { return true; } } return super.onInterceptTouchEvent(event); } @Override public boolean onTouchEvent(MotionEvent event) { if (mFlingToExposeMaster && !mMasterVisible && mGestureDetector.onTouchEvent(event)) { return true; } if (event.getAction() == MotionEvent.ACTION_DOWN && mMasterView != null && mMasterVisible) { // If the master is visible, touching in the detail area should hide the master. if (event.getX() > mTranslateAmount) { showMaster(false, 0); return true; } } return super.onTouchEvent(event); } @Override public void onAnimationStart(Animator animator) { } @Override public void onAnimationEnd(Animator animator) { mIsAnimating = false; mMasterView.setLayerType(LAYER_TYPE_NONE, null); mDetailView.setLayerType(LAYER_TYPE_NONE, null); requestLayout(); if (mShowMasterCompleteRunnable != null) { mShowMasterCompleteRunnable.run(); mShowMasterCompleteRunnable = null; } } @Override public void onAnimationCancel(Animator animator) { mIsAnimating = false; mMasterView.setLayerType(LAYER_TYPE_NONE, null); mDetailView.setLayerType(LAYER_TYPE_NONE, null); requestLayout(); if (mShowMasterCompleteRunnable != null) { mShowMasterCompleteRunnable.run(); mShowMasterCompleteRunnable = null; } } @Override public void onAnimationRepeat(Animator animator) { } private final GestureDetector.OnGestureListener mGestureListener = new GestureDetector.SimpleOnGestureListener() { @Override public boolean onDown(MotionEvent e) { return true; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { ViewConfiguration viewConfig = ViewConfiguration.get(getContext()); float absVelocityX = Math.abs(velocityX); float absVelocityY = Math.abs(velocityY); if (mFlingToExposeMaster && !mMasterVisible && velocityX > 0 && absVelocityX >= absVelocityY // Fling at least as hard in X as in Y && absVelocityX > viewConfig.getScaledMinimumFlingVelocity() && absVelocityX < viewConfig.getScaledMaximumFlingVelocity()) { showMaster(true, 0); return true; } return super.onFling(e1, e2, velocityX, velocityY); } }; }
1162584980-google-io
android/src/com/google/android/apps/iosched/ui/widget/ShowHideMasterLayout.java
Java
asf20
15,609
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.widget; import android.content.Context; import android.util.AttributeSet; import android.widget.Checkable; import android.widget.FrameLayout; /** * A {@link Checkable} {@link FrameLayout}. When this is the root view for an item in a * {@link android.widget.ListView} and the list view has a choice mode of * {@link android.widget.ListView#CHOICE_MODE_MULTIPLE_MODAL }, the list view will * set the item's state to CHECKED and not ACTIVATED. This is important to ensure that we can * use the ACTIVATED state on tablet devices to represent the currently-viewed detail screen, while * allowing multiple-selection. */ public class CheckableFrameLayout extends FrameLayout implements Checkable { private boolean mChecked; public CheckableFrameLayout(Context context) { super(context); } public CheckableFrameLayout(Context context, AttributeSet attrs) { super(context, attrs); } public CheckableFrameLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } private static final int[] CheckedStateSet = { android.R.attr.state_checked }; @Override public boolean isChecked() { return mChecked; } @Override public void setChecked(boolean checked) { mChecked = checked; refreshDrawableState(); } @Override public void toggle() { setChecked(!mChecked); } @Override protected int[] onCreateDrawableState(int extraSpace) { final int[] drawableState = super.onCreateDrawableState(extraSpace + 1); if (isChecked()) { mergeDrawableStates(drawableState, CheckedStateSet); } return drawableState; } }
1162584980-google-io
android/src/com/google/android/apps/iosched/ui/widget/CheckableFrameLayout.java
Java
asf20
2,376
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.widget; import com.google.android.apps.iosched.R; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.widget.ImageView; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * An {@link ImageView} that draws its contents inside a mask and draws a border drawable on top. * This is useful for applying a beveled look to image contents, but is also flexible enough for use * with other desired aesthetics. */ public class BezelImageView extends ImageView { private static final String TAG = makeLogTag(BezelImageView.class); private Paint mMaskedPaint; private Rect mBounds; private RectF mBoundsF; private Drawable mBorderDrawable; private Drawable mMaskDrawable; private boolean mGuardInvalidate; // prevents stack overflows public BezelImageView(Context context) { this(context, null); } public BezelImageView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public BezelImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // Attribute initialization final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.BezelImageView, defStyle, 0); mMaskDrawable = a.getDrawable(R.styleable.BezelImageView_maskDrawable); if (mMaskDrawable == null) { mMaskDrawable = getResources().getDrawable(R.drawable.bezel_mask); } mMaskDrawable.setCallback(this); mBorderDrawable = a.getDrawable(R.styleable.BezelImageView_borderDrawable); if (mBorderDrawable == null) { mBorderDrawable = getResources().getDrawable(R.drawable.bezel_border_default); } mBorderDrawable.setCallback(this); a.recycle(); // Other initialization mMaskedPaint = new Paint(); mMaskedPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP)); } private Bitmap mCached; private void invalidateCache() { if (mBounds == null || mBounds.width() == 0 || mBounds.height() == 0) { return; } if (mCached != null) { mCached.recycle(); mCached = null; } mCached = Bitmap.createBitmap(mBounds.width(), mBounds.height(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(mCached); int sc = canvas.saveLayer(mBoundsF, null, Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.FULL_COLOR_LAYER_SAVE_FLAG); mMaskDrawable.draw(canvas); canvas.saveLayer(mBoundsF, mMaskedPaint, 0); // certain drawables invalidate themselves on draw, e.g. TransitionDrawable sets its alpha // which invalidates itself. to prevent stack overflow errors, we must guard the // invalidation (see specialized behavior when guarded in invalidate() below). mGuardInvalidate = true; super.onDraw(canvas); mGuardInvalidate = false; canvas.restoreToCount(sc); mBorderDrawable.draw(canvas); } @Override protected boolean setFrame(int l, int t, int r, int b) { final boolean changed = super.setFrame(l, t, r, b); mBounds = new Rect(0, 0, r - l, b - t); mBoundsF = new RectF(mBounds); mBorderDrawable.setBounds(mBounds); mMaskDrawable.setBounds(mBounds); if (changed) { invalidateCache(); } return changed; } @Override protected void onDraw(Canvas canvas) { if (mCached == null) { invalidateCache(); } if (mCached != null) { canvas.drawBitmap(mCached, mBounds.left, mBounds.top, null); } //super.onDraw(canvas); } @Override protected void drawableStateChanged() { super.drawableStateChanged(); if (mBorderDrawable.isStateful()) { mBorderDrawable.setState(getDrawableState()); } if (mMaskDrawable.isStateful()) { mMaskDrawable.setState(getDrawableState()); } // TODO: may need to invalidate elsewhere invalidate(); } @Override public void invalidate() { if (mGuardInvalidate) { removeCallbacks(mInvalidateCacheRunnable); postDelayed(mInvalidateCacheRunnable, 16); } else { super.invalidate(); invalidateCache(); } } private Runnable mInvalidateCacheRunnable = new Runnable() { @Override public void run() { invalidateCache(); BezelImageView.super.invalidate(); LOGD(TAG, "delayed invalidate"); } }; }
1162584980-google-io
android/src/com/google/android/apps/iosched/ui/widget/BezelImageView.java
Java
asf20
5,729
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.widget; import android.content.Context; import android.database.DataSetObserver; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.TextView; import java.util.Arrays; import java.util.Comparator; public class SimpleSectionedListAdapter extends BaseAdapter { private boolean mValid = true; private int mSectionResourceId; private LayoutInflater mLayoutInflater; private ListAdapter mBaseAdapter; private SparseArray<Section> mSections = new SparseArray<Section>(); public static class Section { int firstPosition; int sectionedPosition; CharSequence title; public Section(int firstPosition, CharSequence title) { this.firstPosition = firstPosition; this.title = title; } public CharSequence getTitle() { return title; } } public SimpleSectionedListAdapter(Context context, int sectionResourceId, ListAdapter baseAdapter) { mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mSectionResourceId = sectionResourceId; mBaseAdapter = baseAdapter; mBaseAdapter.registerDataSetObserver(new DataSetObserver() { @Override public void onChanged() { mValid = !mBaseAdapter.isEmpty(); notifyDataSetChanged(); } @Override public void onInvalidated() { mValid = false; notifyDataSetInvalidated(); } }); } public void setSections(Section[] sections) { mSections.clear(); Arrays.sort(sections, new Comparator<Section>() { @Override public int compare(Section o, Section o1) { return (o.firstPosition == o1.firstPosition) ? 0 : ((o.firstPosition < o1.firstPosition) ? -1 : 1); } }); int offset = 0; // offset positions for the headers we're adding for (Section section : sections) { section.sectionedPosition = section.firstPosition + offset; mSections.append(section.sectionedPosition, section); ++offset; } notifyDataSetChanged(); } public int positionToSectionedPosition(int position) { int offset = 0; for (int i = 0; i < mSections.size(); i++) { if (mSections.valueAt(i).firstPosition > position) { break; } ++offset; } return position + offset; } public int sectionedPositionToPosition(int sectionedPosition) { if (isSectionHeaderPosition(sectionedPosition)) { return ListView.INVALID_POSITION; } int offset = 0; for (int i = 0; i < mSections.size(); i++) { if (mSections.valueAt(i).sectionedPosition > sectionedPosition) { break; } --offset; } return sectionedPosition + offset; } public boolean isSectionHeaderPosition(int position) { return mSections.get(position) != null; } @Override public int getCount() { return (mValid ? mBaseAdapter.getCount() + mSections.size() : 0); } @Override public Object getItem(int position) { return isSectionHeaderPosition(position) ? mSections.get(position) : mBaseAdapter.getItem(sectionedPositionToPosition(position)); } @Override public long getItemId(int position) { return isSectionHeaderPosition(position) ? Integer.MAX_VALUE - mSections.indexOfKey(position) : mBaseAdapter.getItemId(sectionedPositionToPosition(position)); } @Override public int getItemViewType(int position) { return isSectionHeaderPosition(position) ? getViewTypeCount() - 1 : mBaseAdapter.getItemViewType(position); } @Override public boolean isEnabled(int position) { //noinspection SimplifiableConditionalExpression return isSectionHeaderPosition(position) ? false : mBaseAdapter.isEnabled(sectionedPositionToPosition(position)); } @Override public int getViewTypeCount() { return mBaseAdapter.getViewTypeCount() + 1; // the section headings } @Override public boolean areAllItemsEnabled() { return false; } @Override public boolean hasStableIds() { return mBaseAdapter.hasStableIds(); } @Override public boolean isEmpty() { return mBaseAdapter.isEmpty(); } @Override public View getView(int position, View convertView, ViewGroup parent) { if (isSectionHeaderPosition(position)) { TextView view = (TextView) convertView; if (view == null) { view = (TextView) mLayoutInflater.inflate(mSectionResourceId, parent, false); } view.setText(mSections.get(position).title); return view; } else { return mBaseAdapter.getView(sectionedPositionToPosition(position), convertView, parent); } } }
1162584980-google-io
android/src/com/google/android/apps/iosched/ui/widget/SimpleSectionedListAdapter.java
Java
asf20
6,081
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.UIUtils; import com.actionbarsherlock.app.SherlockListFragment; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.provider.BaseColumns; import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.text.Spannable; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.ListView; import android.widget.TextView; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; import static com.google.android.apps.iosched.util.UIUtils.buildStyledSnippet; /** * A {@link ListFragment} showing a list of developer sandbox companies. */ public class VendorsFragment extends SherlockListFragment implements LoaderManager.LoaderCallbacks<Cursor> { private static final String TAG = makeLogTag(VendorsFragment.class); private static final String STATE_SELECTED_ID = "selectedId"; private Uri mVendorsUri; private CursorAdapter mAdapter; private String mSelectedVendorId; private boolean mHasSetEmptyText = false; public interface Callbacks { /** Return true to select (activate) the vendor in the list, false otherwise. */ public boolean onVendorSelected(String vendorId); } private static Callbacks sDummyCallbacks = new Callbacks() { @Override public boolean onVendorSelected(String vendorId) { return true; } }; private Callbacks mCallbacks = sDummyCallbacks; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { mSelectedVendorId = savedInstanceState.getString(STATE_SELECTED_ID); } reloadFromArguments(getArguments()); } public void reloadFromArguments(Bundle arguments) { // Teardown from previous arguments setListAdapter(null); // Load new arguments final Intent intent = BaseActivity.fragmentArgumentsToIntent(arguments); mVendorsUri = intent.getData(); final int vendorQueryToken; if (mVendorsUri == null) { return; } mAdapter = new VendorsAdapter(getActivity()); vendorQueryToken = VendorsQuery._TOKEN; setListAdapter(mAdapter); // Start background query to load vendors getLoaderManager().initLoader(vendorQueryToken, null, this); } public void setSelectedVendorId(String id) { mSelectedVendorId = id; if (mAdapter != null) { mAdapter.notifyDataSetChanged(); } } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); view.setBackgroundColor(Color.WHITE); final ListView listView = getListView(); listView.setSelector(android.R.color.transparent); listView.setCacheColorHint(Color.WHITE); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (!mHasSetEmptyText) { // Could be a bug, but calling this twice makes it become visible // when it shouldn't be visible. setEmptyText(getString(R.string.empty_vendors)); mHasSetEmptyText = true; } } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (!(activity instanceof Callbacks)) { throw new ClassCastException("Activity must implement fragment's callbacks."); } mCallbacks = (Callbacks) activity; } @Override public void onDetach() { super.onDetach(); mCallbacks = sDummyCallbacks; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mSelectedVendorId != null) { outState.putString(STATE_SELECTED_ID, mSelectedVendorId); } } /** {@inheritDoc} */ @Override public void onListItemClick(ListView l, View v, int position, long id) { final Cursor cursor = (Cursor) mAdapter.getItem(position); String vendorId = cursor.getString(VendorsQuery.VENDOR_ID); if (mCallbacks.onVendorSelected(vendorId)) { mSelectedVendorId = vendorId; mAdapter.notifyDataSetChanged(); } } @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { return new CursorLoader(getActivity(), mVendorsUri, VendorsQuery.PROJECTION, null, null, ScheduleContract.Vendors.DEFAULT_SORT); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if (getActivity() == null) { return; } int token = loader.getId(); if (token == VendorsQuery._TOKEN) { mAdapter.changeCursor(cursor); } else { cursor.close(); } } @Override public void onLoaderReset(Loader<Cursor> cursor) { } /** * {@link CursorAdapter} that renders a {@link VendorsQuery}. */ private class VendorsAdapter extends CursorAdapter { public VendorsAdapter(Context context) { super(context, null, false); } /** {@inheritDoc} */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return getActivity().getLayoutInflater().inflate(R.layout.list_item_vendor, parent, false); } /** {@inheritDoc} */ @Override public void bindView(View view, Context context, Cursor cursor) { UIUtils.setActivatedCompat(view, cursor.getString(VendorsQuery.VENDOR_ID) .equals(mSelectedVendorId)); ((TextView) view.findViewById(R.id.vendor_name)).setText( cursor.getString(VendorsQuery.NAME)); } } /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Vendors} * query parameters. */ private interface VendorsQuery { int _TOKEN = 0x1; String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Vendors.VENDOR_ID, ScheduleContract.Vendors.VENDOR_NAME, }; int _ID = 0; int VENDOR_ID = 1; int NAME = 2; } }
1162584980-google-io
android/src/com/google/android/apps/iosched/ui/VendorsFragment.java
Java
asf20
7,539
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.SessionsHelper; import com.google.android.apps.iosched.util.UIUtils; import com.google.android.apps.iosched.util.actionmodecompat.ActionMode; import com.google.android.apps.iosched.util.actionmodecompat.MultiChoiceModeListener; import com.actionbarsherlock.app.SherlockListFragment; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.database.ContentObserver; import android.database.Cursor; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.SystemClock; import android.provider.BaseColumns; import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.text.Spannable; import android.text.TextUtils; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.LinkedHashSet; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.LOGV; import static com.google.android.apps.iosched.util.LogUtils.LOGW; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; import static com.google.android.apps.iosched.util.UIUtils.buildStyledSnippet; import static com.google.android.apps.iosched.util.UIUtils.formatSessionSubtitle; /** * A {@link ListFragment} showing a list of sessions. This fragment supports multiple-selection * using the contextual action bar (on API 11+ devices), and also supports a separate 'activated' * state for indicating the currently-opened detail view on tablet devices. */ public class SessionsFragment extends SherlockListFragment implements LoaderManager.LoaderCallbacks<Cursor>, MultiChoiceModeListener { private static final String TAG = makeLogTag(SessionsFragment.class); private static final String STATE_SELECTED_ID = "selectedId"; private CursorAdapter mAdapter; private String mSelectedSessionId; private MenuItem mStarredMenuItem; private MenuItem mMapMenuItem; private MenuItem mShareMenuItem; private MenuItem mSocialStreamMenuItem; private boolean mHasSetEmptyText = false; private int mSessionQueryToken; private LinkedHashSet<Integer> mSelectedSessionPositions = new LinkedHashSet<Integer>(); private Handler mHandler = new Handler(); public interface Callbacks { /** Return true to select (activate) the session in the list, false otherwise. */ public boolean onSessionSelected(String sessionId); } private static Callbacks sDummyCallbacks = new Callbacks() { @Override public boolean onSessionSelected(String sessionId) { return true; } }; private Callbacks mCallbacks = sDummyCallbacks; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { mSelectedSessionId = savedInstanceState.getString(STATE_SELECTED_ID); } reloadFromArguments(getArguments()); } protected void reloadFromArguments(Bundle arguments) { // Teardown from previous arguments setListAdapter(null); // Load new arguments final Intent intent = BaseActivity.fragmentArgumentsToIntent(arguments); final Uri sessionsUri = intent.getData(); if (sessionsUri == null) { return; } if (!ScheduleContract.Sessions.isSearchUri(sessionsUri)) { mAdapter = new SessionsAdapter(getActivity()); mSessionQueryToken = SessionsQuery._TOKEN; } else { mAdapter = new SearchAdapter(getActivity()); mSessionQueryToken = SearchQuery._TOKEN; } setListAdapter(mAdapter); // Force start background query to load sessions getLoaderManager().restartLoader(mSessionQueryToken, arguments, this); } public void setSelectedSessionId(String id) { mSelectedSessionId = id; if (mAdapter != null) { mAdapter.notifyDataSetChanged(); } } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); view.setBackgroundColor(Color.WHITE); final ListView listView = getListView(); listView.setSelector(android.R.color.transparent); listView.setCacheColorHint(Color.WHITE); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (!mHasSetEmptyText) { // Could be a bug, but calling this twice makes it become visible // when it shouldn't // be visible. setEmptyText(getString(R.string.empty_sessions)); mHasSetEmptyText = true; } ActionMode.setMultiChoiceMode(getListView(), getActivity(), this); } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (!(activity instanceof Callbacks)) { throw new ClassCastException("Activity must implement fragment's callbacks."); } mCallbacks = (Callbacks) activity; activity.getContentResolver().registerContentObserver( ScheduleContract.Sessions.CONTENT_URI, true, mObserver); } @Override public void onDetach() { super.onDetach(); mCallbacks = sDummyCallbacks; getActivity().getContentResolver().unregisterContentObserver(mObserver); } @Override public void onResume() { super.onResume(); mHandler.post(mRefreshSessionsRunnable); } @Override public void onPause() { super.onPause(); mHandler.removeCallbacks(mRefreshSessionsRunnable); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mSelectedSessionId != null) { outState.putString(STATE_SELECTED_ID, mSelectedSessionId); } } /** {@inheritDoc} */ @Override public void onListItemClick(ListView l, View v, int position, long id) { final Cursor cursor = (Cursor) mAdapter.getItem(position); String sessionId = cursor.getString(cursor.getColumnIndex( ScheduleContract.Sessions.SESSION_ID)); if (mCallbacks.onSessionSelected(sessionId)) { mSelectedSessionId = sessionId; mAdapter.notifyDataSetChanged(); } } // LoaderCallbacks interface @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { final Intent intent = BaseActivity.fragmentArgumentsToIntent(data); final Uri sessionsUri = intent.getData(); Loader<Cursor> loader = null; if (id == SessionsQuery._TOKEN) { loader = new CursorLoader(getActivity(), sessionsUri, SessionsQuery.PROJECTION, null, null, ScheduleContract.Sessions.DEFAULT_SORT); } else if (id == SearchQuery._TOKEN) { loader = new CursorLoader(getActivity(), sessionsUri, SearchQuery.PROJECTION, null, null, ScheduleContract.Sessions.DEFAULT_SORT); } return loader; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if (getActivity() == null) { return; } int token = loader.getId(); if (token == SessionsQuery._TOKEN || token == SearchQuery._TOKEN) { mAdapter.changeCursor(cursor); Bundle arguments = getArguments(); if (arguments != null && arguments.containsKey("_uri")) { String uri = arguments.get("_uri").toString(); if(uri != null && uri.contains("blocks")) { String title = arguments.getString(Intent.EXTRA_TITLE); if (title == null) { title = (String) this.getActivity().getTitle(); } EasyTracker.getTracker().trackView("Session Block: " + title); LOGD("Tracker", "Session Block: " + title); } } } else { LOGD(TAG, "Query complete, Not Actionable: " + token); cursor.close(); } } @Override public void onLoaderReset(Loader<Cursor> loader) { } // MultiChoiceModeListener interface @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { SessionsHelper helper = new SessionsHelper(getActivity()); mode.finish(); switch (item.getItemId()) { case R.id.menu_map: { // multiple selection not supported int position = mSelectedSessionPositions.iterator().next(); Cursor cursor = (Cursor) mAdapter.getItem(position); String roomId = cursor.getString(SessionsQuery.ROOM_ID); helper.startMapActivity(roomId); String title = cursor.getString(SessionsQuery.TITLE); EasyTracker.getTracker().trackEvent( "Session", "Mapped", title, 0L); LOGV(TAG, "Starred: " + title); return true; } case R.id.menu_star: { // multiple selection supported boolean starred = false; int numChanged = 0; for (int position : mSelectedSessionPositions) { Cursor cursor = (Cursor) mAdapter.getItem(position); String title = cursor.getString(SessionsQuery.TITLE); String sessionId = cursor.getString(SessionsQuery.SESSION_ID); Uri sessionUri = ScheduleContract.Sessions.buildSessionUri(sessionId); starred = cursor.getInt(SessionsQuery.STARRED) == 0; helper.setSessionStarred(sessionUri, starred, title); ++numChanged; EasyTracker.getTracker().trackEvent( "Session", starred ? "Starred" : "Unstarred", title, 0L); LOGV(TAG, "Starred: " + title); } Toast.makeText( getActivity(), getResources().getQuantityString(starred ? R.plurals.toast_added_to_schedule : R.plurals.toast_removed_from_schedule, numChanged, numChanged), Toast.LENGTH_SHORT).show(); setSelectedSessionStarred(starred); return true; } case R.id.menu_share: { // multiple selection not supported int position = mSelectedSessionPositions.iterator().next(); // On ICS+ devices, we normally won't reach this as ShareActionProvider will handle // sharing. Cursor cursor = (Cursor) mAdapter.getItem(position); new SessionsHelper(getActivity()).shareSession(getActivity(), R.string.share_template, cursor.getString(SessionsQuery.TITLE), cursor.getString(SessionsQuery.HASHTAGS), cursor.getString(SessionsQuery.URL)); return true; } case R.id.menu_social_stream: StringBuilder hashtags = new StringBuilder(); for (int position : mSelectedSessionPositions) { Cursor cursor = (Cursor) mAdapter.getItem(position); String term = cursor.getString(SessionsQuery.HASHTAGS); if (!term.startsWith("#")) { term = "#" + term; } if (hashtags.length() > 0) { hashtags.append(" OR "); } hashtags.append(term); String title = cursor.getString(SessionsQuery.TITLE); EasyTracker.getTracker().trackEvent( "Session", "Mapped", title, 0L); LOGV(TAG, "Starred: " + title); } helper.startSocialStream(hashtags.toString()); return true; default: LOGW(TAG, "CAB unknown selection=" + item.getItemId()); return false; } } @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { MenuInflater inflater = mode.getMenuInflater(); inflater.inflate(R.menu.sessions_context, menu); mStarredMenuItem = menu.findItem(R.id.menu_star); mMapMenuItem = menu.findItem(R.id.menu_map); mShareMenuItem = menu.findItem(R.id.menu_share); mSocialStreamMenuItem = menu.findItem(R.id.menu_social_stream); mSelectedSessionPositions.clear(); return true; } @Override public void onDestroyActionMode(ActionMode mode) {} @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return false; } @Override public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) { if (checked) { mSelectedSessionPositions.add(position); } else { mSelectedSessionPositions.remove(position); } int numSelectedSessions = mSelectedSessionPositions.size(); mode.setTitle(getResources().getQuantityString( R.plurals.title_selected_sessions, numSelectedSessions, numSelectedSessions)); if (numSelectedSessions == 1) { // activate all the menu item mMapMenuItem.setVisible(true); mShareMenuItem.setVisible(true); mSocialStreamMenuItem.setVisible(true); mStarredMenuItem.setVisible(true); position = mSelectedSessionPositions.iterator().next(); Cursor cursor = (Cursor) mAdapter.getItem(position); boolean starred = cursor.getInt(SessionsQuery.STARRED) != 0; setSelectedSessionStarred(starred); } else { mMapMenuItem.setVisible(false); mShareMenuItem.setVisible(false); mSocialStreamMenuItem.setVisible(false); boolean allStarred = true; boolean allUnstarred = true; for (int pos : mSelectedSessionPositions) { Cursor cursor = (Cursor) mAdapter.getItem(pos); boolean starred = cursor.getInt(SessionsQuery.STARRED) != 0; allStarred = allStarred && starred; allUnstarred = allUnstarred && !starred; } if (allStarred) { setSelectedSessionStarred(true); mStarredMenuItem.setVisible(true); } else if (allUnstarred) { setSelectedSessionStarred(false); mStarredMenuItem.setVisible(true); } else { mStarredMenuItem.setVisible(false); } } } private void setSelectedSessionStarred(boolean starred) { mStarredMenuItem.setTitle(starred ? R.string.description_remove_schedule : R.string.description_add_schedule); mStarredMenuItem.setIcon(starred ? R.drawable.ic_action_remove_schedule : R.drawable.ic_action_add_schedule); } private final Runnable mRefreshSessionsRunnable = new Runnable() { public void run() { if (mAdapter != null) { // This is used to refresh session title colors. mAdapter.notifyDataSetChanged(); } // Check again on the next quarter hour, with some padding to // account for network // time differences. long nextQuarterHour = (SystemClock.uptimeMillis() / 900000 + 1) * 900000 + 5000; mHandler.postAtTime(mRefreshSessionsRunnable, nextQuarterHour); } }; private final ContentObserver mObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { if (getActivity() == null) { return; } Loader<Cursor> loader = getLoaderManager().getLoader(mSessionQueryToken); if (loader != null) { loader.forceLoad(); } } }; /** * {@link CursorAdapter} that renders a {@link SessionsQuery}. */ private class SessionsAdapter extends CursorAdapter { public SessionsAdapter(Context context) { super(context, null, false); } /** {@inheritDoc} */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return getActivity().getLayoutInflater().inflate(R.layout.list_item_session, parent, false); } /** {@inheritDoc} */ @Override public void bindView(View view, Context context, Cursor cursor) { String sessionId = cursor.getString(SessionsQuery.SESSION_ID); if (sessionId == null) { return; } if (sessionId.equals(mSelectedSessionId)){ UIUtils.setActivatedCompat(view, true); } else { UIUtils.setActivatedCompat(view, false); } final TextView titleView = (TextView) view.findViewById(R.id.session_title); final TextView subtitleView = (TextView) view.findViewById(R.id.session_subtitle); final String sessionTitle = cursor.getString(SessionsQuery.TITLE); titleView.setText(sessionTitle); // Format time block this session occupies final long blockStart = cursor.getLong(SessionsQuery.BLOCK_START); final long blockEnd = cursor.getLong(SessionsQuery.BLOCK_END); final String roomName = cursor.getString(SessionsQuery.ROOM_NAME); final String subtitle = formatSessionSubtitle( sessionTitle, blockStart, blockEnd, roomName, context); final boolean starred = cursor.getInt(SessionsQuery.STARRED) != 0; view.findViewById(R.id.indicator_in_schedule).setVisibility( starred ? View.VISIBLE : View.INVISIBLE); final boolean hasLivestream = !TextUtils.isEmpty( cursor.getString(SessionsQuery.LIVESTREAM_URL)); // Show past/present/future and livestream status for this block. UIUtils.updateTimeAndLivestreamBlockUI(context, blockStart, blockEnd, hasLivestream, view.findViewById(R.id.list_item_session), titleView, subtitleView, subtitle); } } /** * {@link CursorAdapter} that renders a {@link SearchQuery}. */ private class SearchAdapter extends CursorAdapter { public SearchAdapter(Context context) { super(context, null, false); } /** {@inheritDoc} */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return getActivity().getLayoutInflater().inflate(R.layout.list_item_session, parent, false); } /** {@inheritDoc} */ @Override public void bindView(View view, Context context, Cursor cursor) { UIUtils.setActivatedCompat(view, cursor.getString(SessionsQuery.SESSION_ID) .equals(mSelectedSessionId)); ((TextView) view.findViewById(R.id.session_title)).setText(cursor .getString(SearchQuery.TITLE)); final String snippet = cursor.getString(SearchQuery.SEARCH_SNIPPET); final Spannable styledSnippet = buildStyledSnippet(snippet); ((TextView) view.findViewById(R.id.session_subtitle)).setText(styledSnippet); final boolean starred = cursor.getInt(SearchQuery.STARRED) != 0; view.findViewById(R.id.indicator_in_schedule).setVisibility( starred ? View.VISIBLE : View.INVISIBLE); } } /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Sessions} * query parameters. */ private interface SessionsQuery { int _TOKEN = 0x1; String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Sessions.SESSION_ID, ScheduleContract.Sessions.SESSION_TITLE, ScheduleContract.Sessions.SESSION_STARRED, ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_END, ScheduleContract.Rooms.ROOM_NAME, ScheduleContract.Rooms.ROOM_ID, ScheduleContract.Sessions.SESSION_HASHTAGS, ScheduleContract.Sessions.SESSION_URL, ScheduleContract.Sessions.SESSION_LIVESTREAM_URL, }; int _ID = 0; int SESSION_ID = 1; int TITLE = 2; int STARRED = 3; int BLOCK_START = 4; int BLOCK_END = 5; int ROOM_NAME = 6; int ROOM_ID = 7; int HASHTAGS = 8; int URL = 9; int LIVESTREAM_URL = 10; } /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Sessions} * search query parameters. */ private interface SearchQuery { int _TOKEN = 0x3; String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Sessions.SESSION_ID, ScheduleContract.Sessions.SESSION_TITLE, ScheduleContract.Sessions.SESSION_STARRED, ScheduleContract.Sessions.SEARCH_SNIPPET, ScheduleContract.Sessions.SESSION_LEVEL, ScheduleContract.Rooms.ROOM_NAME, ScheduleContract.Rooms.ROOM_ID, ScheduleContract.Sessions.SESSION_HASHTAGS, ScheduleContract.Sessions.SESSION_URL }; int _ID = 0; int SESSION_ID = 1; int TITLE = 2; int STARRED = 3; int SEARCH_SNIPPET = 4; int LEVEL = 5; int ROOM_NAME = 6; int ROOM_ID = 7; int HASHTAGS = 8; int URL = 9; } }
1162584980-google-io
android/src/com/google/android/apps/iosched/ui/SessionsFragment.java
Java
asf20
23,652
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.Config; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.provider.ScheduleContract.Tracks; import com.google.android.apps.iosched.util.SessionsHelper; import com.google.android.apps.iosched.util.UIUtils; import com.google.android.youtube.api.YouTube; import com.google.android.youtube.api.YouTubePlayer; import com.google.android.youtube.api.YouTubePlayerSupportFragment; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.actionbarsherlock.view.Window; import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.database.Cursor; import android.graphics.Color; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.provider.BaseColumns; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentTransaction; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.app.NavUtils; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.view.ViewPager; import android.support.v4.widget.CursorAdapter; import android.text.TextUtils; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.TabHost; import android.widget.TabWidget; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.LOGE; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * An activity that displays the session live stream video which is pulled in from YouTube. The * UI adapts for both phone and tablet. As we want to prevent the YouTube player from restarting * and buffering again on orientation change, we handle configuration changes manually. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class SessionLivestreamActivity extends BaseActivity implements LoaderCallbacks<Cursor>, YouTubePlayer.OnPlaybackEventsListener, YouTubePlayer.OnFullscreenListener, ActionBar.OnNavigationListener { private static final String TAG = makeLogTag(SessionLivestreamActivity.class); private static final String EXTRA_PREFIX = "com.google.android.iosched.extra."; public static final String EXTRA_YOUTUBE_URL = EXTRA_PREFIX + "youtube_url"; public static final String EXTRA_TRACK = EXTRA_PREFIX + "track"; public static final String EXTRA_TITLE = EXTRA_PREFIX + "title"; public static final String EXTRA_ABSTRACT = EXTRA_PREFIX + "abstract"; public static final String KEYNOTE_TRACK_NAME = "Keynote"; private static final String LOADER_SESSIONS_ARG = "futureSessions"; private static final String TAG_SESSION_SUMMARY = "session_summary"; private static final String TAG_CAPTIONS = "captions"; private static final int TABNUM_SESSION_SUMMARY = 0; private static final int TABNUM_SOCIAL_STREAM = 1; private static final int TABNUM_LIVE_CAPTIONS = 2; private static final String EXTRA_TAB_STATE = "tag"; private static final int STREAM_REFRESH_TIME = 5 * 60 * 1000; // 5 minutes private boolean mIsTablet; private boolean mIsFullscreen = false; private boolean mLoadFromExtras = false; private boolean mTrackPlay = true; private int mNormalScreenOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED; private TabHost mTabHost; private TabsAdapter mTabsAdapter; private YouTubePlayerSupportFragment mYouTubePlayer; private LinearLayout mPlayerContainer; private String mYouTubeVideoId; private LinearLayout mMainLayout; private LinearLayout mVideoLayout; private LinearLayout mExtraLayout; private FrameLayout mSummaryLayout; private FrameLayout mFullscreenCaptions; private MenuItem mCaptionsMenuItem; private MenuItem mShareMenuItem; private Runnable mShareMenuDeferredSetup; private Runnable mSessionSummaryDeferredSetup; private SessionShareData mSessionShareData; private boolean mSessionsFound; private boolean isKeynote = false; private Handler mHandler = new Handler(); private LivestreamAdapter mLivestreamAdapter; private Uri mSessionUri; private String mSessionId; private String mTrackName; @Override protected void onCreate(Bundle savedInstanceState) { if (UIUtils.hasICS()) { // We can't use this mode on HC as compatible ActionBar doesn't work well with the YT // player in full screen mode (no overlays allowed). requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY); } super.onCreate(savedInstanceState); YouTube.initialize(this, Config.YOUTUBE_API_KEY); setContentView(R.layout.activity_session_livestream); mIsTablet = UIUtils.isHoneycombTablet(this); // Set up YouTube player mYouTubePlayer = (YouTubePlayerSupportFragment) getSupportFragmentManager() .findFragmentById(R.id.livestream_player); mYouTubePlayer.enableCustomFullscreen(this); mYouTubePlayer.setOnPlaybackEventsListener(this); int fullscreenControlFlags = YouTubePlayer.FULLSCREEN_FLAG_CONTROL_SYSTEM_UI | YouTubePlayer.FULLSCREEN_FLAG_CONTROL_ORIENTATION; if (!mIsTablet) { fullscreenControlFlags |= YouTubePlayer.FULLSCREEN_FLAG_FULLSCREEN_WHEN_DEVICE_LANDSCAPE; setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT); } mYouTubePlayer.setFullscreenControlFlags(fullscreenControlFlags); // Views that are common over all layouts mMainLayout = (LinearLayout) findViewById(R.id.livestream_mainlayout); adjustMainLayoutForActionBar(); mPlayerContainer = (LinearLayout) findViewById(R.id.livestream_player_container); mFullscreenCaptions = (FrameLayout) findViewById(R.id.fullscreen_captions); final LayoutParams params = (LayoutParams) mFullscreenCaptions.getLayoutParams(); params.setMargins(0, getActionBarHeightPx(), 0, getActionBarHeightPx()); mFullscreenCaptions.setLayoutParams(params); ViewPager viewPager = (ViewPager) findViewById(R.id.pager); viewPager.setOffscreenPageLimit(2); viewPager.setPageMarginDrawable(R.drawable.grey_border_inset_lr); viewPager.setPageMargin(getResources() .getDimensionPixelSize(R.dimen.page_margin_width)); // Set up tabs w/viewpager mTabHost = (TabHost) findViewById(android.R.id.tabhost); mTabHost.setup(); mTabsAdapter = new TabsAdapter(this, mTabHost, viewPager); if (mIsTablet) { // Tablet UI specific views getSupportFragmentManager().beginTransaction().add(R.id.livestream_summary, new SessionSummaryFragment(), TAG_SESSION_SUMMARY).commit(); mVideoLayout = (LinearLayout) findViewById(R.id.livestream_videolayout); mExtraLayout = (LinearLayout) findViewById(R.id.livestream_extralayout); mSummaryLayout = (FrameLayout) findViewById(R.id.livestream_summary); } else { // Handset UI specific views mTabsAdapter.addTab( getString(R.string.session_livestream_info), new SessionSummaryFragment(), TABNUM_SESSION_SUMMARY); } mTabsAdapter.addTab(getString(R.string.title_stream), new SocialStreamFragment(), TABNUM_SOCIAL_STREAM); mTabsAdapter.addTab(getString(R.string.session_livestream_captions), new SessionLiveCaptionsFragment(), TABNUM_LIVE_CAPTIONS); if (savedInstanceState != null) { mTabHost.setCurrentTabByTag(savedInstanceState.getString(EXTRA_TAB_STATE)); } // Reload all other data in this activity reloadFromIntent(getIntent()); // Update layout based on current configuration updateLayout(getResources().getConfiguration()); // Set up action bar if (!mLoadFromExtras) { // Start sessions query to populate action bar navigation spinner getSupportLoaderManager().initLoader(SessionsQuery._TOKEN, null, this); // Set up action bar mLivestreamAdapter = new LivestreamAdapter(this); final ActionBar actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); actionBar.setListNavigationCallbacks(mLivestreamAdapter, this); actionBar.setDisplayShowTitleEnabled(false); } } @Override protected void onResume() { super.onResume(); if (mSessionSummaryDeferredSetup != null) { mSessionSummaryDeferredSetup.run(); mSessionSummaryDeferredSetup = null; } mHandler.postDelayed(mStreamRefreshRunnable, STREAM_REFRESH_TIME); } @Override protected void onPause() { super.onPause(); mHandler.removeCallbacks(mStreamRefreshRunnable); } /** * Reloads all data in the activity and fragments from a given intent * @param intent The intent to load from */ private void reloadFromIntent(Intent intent) { final String youtubeUrl = intent.getStringExtra(EXTRA_YOUTUBE_URL); // Check if youtube url is set as an extra first if (youtubeUrl != null) { mLoadFromExtras = true; String trackName = intent.getStringExtra(EXTRA_TRACK); String actionBarTitle; if (trackName == null) { actionBarTitle = getString(R.string.session_livestream_title); } else { actionBarTitle = trackName + " - " + getString(R.string.session_livestream_title); } getSupportActionBar().setTitle(actionBarTitle); updateSessionViews(youtubeUrl, intent.getStringExtra(EXTRA_TITLE), intent.getStringExtra(EXTRA_ABSTRACT), UIUtils.CONFERENCE_HASHTAG, trackName); } else { // Otherwise load from session uri reloadFromUri(intent.getData()); } } /** * Reloads all data in the activity and fragments from a given uri * @param newUri The session uri to load from */ private void reloadFromUri(Uri newUri) { mSessionUri = newUri; if (mSessionUri != null && mSessionUri.getPathSegments().size() >= 2) { mSessionId = Sessions.getSessionId(mSessionUri); getSupportLoaderManager().restartLoader(SessionSummaryQuery._TOKEN, null, this); } else { // No session uri, get out mSessionUri = null; navigateUpOrFinish(); } } /** * Helper method to start this activity using only extras (rather than session uri). * @param context The package context * @param youtubeUrl The youtube url or video id to load * @param track The track title (appears as part of action bar title), can be null * @param title The title to show in the session info fragment, can be null * @param sessionAbstract The session abstract to show in the session info fragment, can be null */ public static void startFromExtras(Context context, String youtubeUrl, String track, String title, String sessionAbstract) { if (youtubeUrl == null) { return; } final Intent i = new Intent(); i.setClass(context, SessionLivestreamActivity.class); i.putExtra(EXTRA_YOUTUBE_URL, youtubeUrl); i.putExtra(EXTRA_TRACK, track); i.putExtra(EXTRA_TITLE, title); i.putExtra(EXTRA_ABSTRACT, sessionAbstract); context.startActivity(i); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mTabHost != null) { outState.putString(EXTRA_TAB_STATE, mTabHost.getCurrentTabTag()); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getSupportMenuInflater().inflate(R.menu.session_livestream, menu); mCaptionsMenuItem = menu.findItem(R.id.menu_captions); mShareMenuItem = menu.findItem(R.id.menu_share); if (mShareMenuDeferredSetup != null) { mShareMenuDeferredSetup.run(); } if (!mIsTablet && Configuration.ORIENTATION_LANDSCAPE == getResources().getConfiguration().orientation) { mCaptionsMenuItem.setVisible(true); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: if (mIsFullscreen) { mYouTubePlayer.setFullscreen(false); } else { navigateUpOrFinish(); } return true; case R.id.menu_captions: if (mIsFullscreen) { if (mFullscreenCaptions.getVisibility() == View.GONE) { mFullscreenCaptions.setVisibility(View.VISIBLE); SessionLiveCaptionsFragment captionsFragment; captionsFragment = (SessionLiveCaptionsFragment) getSupportFragmentManager().findFragmentByTag(TAG_CAPTIONS); if (captionsFragment == null) { captionsFragment = new SessionLiveCaptionsFragment(); captionsFragment.setDarkTheme(true); FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.add(R.id.fullscreen_captions, captionsFragment, TAG_CAPTIONS); ft.commit(); } captionsFragment.setTrackName(mTrackName); return true; } } mFullscreenCaptions.setVisibility(View.GONE); break; case R.id.menu_share: if (mSessionShareData != null) { new SessionsHelper(this).shareSession(this, R.string.share_livestream_template, mSessionShareData.SESSION_TITLE, mSessionShareData.SESSION_HASHTAG, mSessionShareData.SESSION_URL); return true; } break; } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { if (mIsFullscreen) { // Exit full screen mode on back key mYouTubePlayer.setFullscreen(false); } else { super.onBackPressed(); } } @Override public void onConfigurationChanged(Configuration newConfig) { // Need to handle configuration changes so as not to interrupt YT player and require // buffering again updateLayout(newConfig); super.onConfigurationChanged(newConfig); } @Override public boolean onNavigationItemSelected(int itemPosition, long itemId) { final Cursor cursor = (Cursor) mLivestreamAdapter.getItem(itemPosition); setActionBarColor(cursor.getInt(SessionsQuery.TRACK_COLOR)); final String sessionId = cursor.getString(SessionsQuery.SESSION_ID); if (sessionId != null) { reloadFromUri(Sessions.buildSessionUri(sessionId)); return true; } return false; } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { switch (id) { case SessionSummaryQuery._TOKEN: return new CursorLoader(this, Sessions.buildWithTracksUri(mSessionId), SessionSummaryQuery.PROJECTION, null, null, null); case SessionsQuery._TOKEN: boolean futureSessions = false; if (args != null) { futureSessions = args.getBoolean(LOADER_SESSIONS_ARG, false); } final long currentTime = UIUtils.getCurrentTime(this); String selection = Sessions.LIVESTREAM_SELECTION + " and "; String[] selectionArgs; if (!futureSessions) { selection += Sessions.AT_TIME_SELECTION; selectionArgs = Sessions.buildAtTimeSelectionArgs(currentTime); } else { selection += Sessions.UPCOMING_SELECTION; selectionArgs = Sessions.buildUpcomingSelectionArgs(currentTime); } return new CursorLoader(this, Sessions.buildWithTracksUri(), SessionsQuery.PROJECTION, selection, selectionArgs, null); } return null; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { switch (loader.getId()) { case SessionSummaryQuery._TOKEN: loadSession(data); break; case SessionsQuery._TOKEN: mLivestreamAdapter.swapCursor(data); if (data != null && data.getCount() > 0) { mSessionsFound = true; final int selected = locateSelectedItem(data); getSupportActionBar().setSelectedNavigationItem(selected); } else if (mSessionsFound) { mSessionsFound = false; final Bundle bundle = new Bundle(); bundle.putBoolean(LOADER_SESSIONS_ARG, true); getSupportLoaderManager().restartLoader(SessionsQuery._TOKEN, bundle, this); } else { navigateUpOrFinish(); } break; } } /** * Locates which item should be selected in the action bar drop-down spinner based on the * current active session uri * @param data The data * @return The row num of the item that should be selected or 0 if not found */ private int locateSelectedItem(Cursor data) { int selected = 0; if (data != null && (mSessionId != null || mTrackName != null)) { final boolean findNextSessionByTrack = mTrackName != null; while (data.moveToNext()) { if (findNextSessionByTrack) { if (mTrackName.equals(data.getString(SessionsQuery.TRACK_NAME))) { selected = data.getPosition(); mTrackName = null; break; } } else { if (mSessionId.equals(data.getString(SessionsQuery.SESSION_ID))) { selected = data.getPosition(); } } } } return selected; } @Override public void onLoaderReset(Loader<Cursor> loader) { switch (loader.getId()) { case SessionsQuery._TOKEN: mLivestreamAdapter.swapCursor(null); break; } } @Override public void onFullscreen(boolean fullScreen) { layoutFullscreenVideo(fullScreen); } @Override public void onLoaded(String s) { } @Override public void onPlaying() { } @Override public void onPaused() { } @Override public void onBuffering(boolean b) { } @Override public void onEnded() { } @Override public void onError() { Toast.makeText(this, R.string.session_livestream_error, Toast.LENGTH_LONG).show(); } private void loadSession(Cursor data) { if (data != null && data.moveToFirst()) { mTrackName = data.getString(SessionSummaryQuery.TRACK_NAME); if (TextUtils.isEmpty(mTrackName)) { mTrackName = KEYNOTE_TRACK_NAME; isKeynote = true; } final long currentTime = UIUtils.getCurrentTime(this); if (currentTime > data.getLong(SessionSummaryQuery.BLOCK_END)) { getSupportLoaderManager().restartLoader(SessionsQuery._TOKEN, null, this); return; } updateTagStreamFragment(data.getString(SessionSummaryQuery.HASHTAGS)); updateSessionViews( data.getString(SessionSummaryQuery.LIVESTREAM_URL), data.getString(SessionSummaryQuery.TITLE), data.getString(SessionSummaryQuery.ABSTRACT), data.getString(SessionSummaryQuery.HASHTAGS), mTrackName); } } /** * Updates views that rely on session data from explicit strings. */ private void updateSessionViews(final String youtubeUrl, final String title, final String sessionAbstract, final String hashTag, final String trackName) { if (youtubeUrl == null) { // Get out, nothing to do here navigateUpOrFinish(); return; } mTrackName = trackName; String youtubeVideoId = youtubeUrl; if (youtubeUrl.startsWith("http")) { final Uri youTubeUri = Uri.parse(youtubeUrl); youtubeVideoId = youTubeUri.getQueryParameter("v"); } playVideo(youtubeVideoId); if (mTrackPlay) { EasyTracker.getTracker().trackView("Live Streaming: " + title); LOGD("Tracker", "Live Streaming: " + title); } final String newYoutubeUrl = Config.YOUTUBE_SHARE_URL_PREFIX + youtubeVideoId; mSessionShareData = new SessionShareData(title, hashTag, newYoutubeUrl); mShareMenuDeferredSetup = new Runnable() { @Override public void run() { new SessionsHelper(SessionLivestreamActivity.this) .tryConfigureShareMenuItem(mShareMenuItem, R.string.share_livestream_template, title, hashTag, newYoutubeUrl); } }; if (mShareMenuItem != null) { mShareMenuDeferredSetup.run(); mShareMenuDeferredSetup = null; } mSessionSummaryDeferredSetup = new Runnable() { @Override public void run() { updateSessionSummaryFragment(title, sessionAbstract); updateSessionLiveCaptionsFragment(trackName); } }; if (!mLoadFromExtras) { mSessionSummaryDeferredSetup.run(); mSessionSummaryDeferredSetup = null; } } private void updateSessionSummaryFragment(String title, String sessionAbstract) { SessionSummaryFragment sessionSummaryFragment; if (mIsTablet) { sessionSummaryFragment = (SessionSummaryFragment) getSupportFragmentManager().findFragmentByTag(TAG_SESSION_SUMMARY); } else { sessionSummaryFragment = (SessionSummaryFragment) mTabsAdapter.mFragments.get(TABNUM_SESSION_SUMMARY); } if (sessionSummaryFragment != null) { sessionSummaryFragment.setSessionSummaryInfo( isKeynote ? getString(R.string.session_livestream_keynote_title, title) : title, (isKeynote && TextUtils.isEmpty(sessionAbstract)) ? getString(R.string.session_livestream_keynote_desc) : sessionAbstract); } } Runnable mStreamRefreshRunnable = new Runnable() { @Override public void run() { if (mTabsAdapter != null && mTabsAdapter.mFragments != null) { final SocialStreamFragment socialStreamFragment = (SocialStreamFragment) mTabsAdapter.mFragments.get(TABNUM_SOCIAL_STREAM); if (socialStreamFragment != null) { socialStreamFragment.refresh(); } } mHandler.postDelayed(mStreamRefreshRunnable, STREAM_REFRESH_TIME); } }; private void updateTagStreamFragment(String trackHashTag) { String hashTags = UIUtils.CONFERENCE_HASHTAG; if (!TextUtils.isEmpty(trackHashTag)) { hashTags += " " + trackHashTag; } final SocialStreamFragment socialStreamFragment = (SocialStreamFragment) mTabsAdapter.mFragments.get(TABNUM_SOCIAL_STREAM); if (socialStreamFragment != null) { socialStreamFragment.refresh(hashTags); } } private void updateSessionLiveCaptionsFragment(String trackName) { final SessionLiveCaptionsFragment captionsFragment = (SessionLiveCaptionsFragment) mTabsAdapter.mFragments.get(TABNUM_LIVE_CAPTIONS); if (captionsFragment != null) { captionsFragment.setTrackName(trackName); } } private void playVideo(String videoId) { if ((TextUtils.isEmpty(mYouTubeVideoId) || !mYouTubeVideoId.equals(videoId)) && !TextUtils.isEmpty(videoId)) { mYouTubeVideoId = videoId; mYouTubePlayer.loadVideo(mYouTubeVideoId); mTrackPlay = true; if (mSessionShareData != null) { mSessionShareData.SESSION_URL = Config.YOUTUBE_SHARE_URL_PREFIX + mYouTubeVideoId; } } } private void navigateUpOrFinish() { if (mLoadFromExtras || isKeynote) { final Intent homeIntent = new Intent(); homeIntent.setClass(this, HomeActivity.class); NavUtils.navigateUpTo(this, homeIntent); } else if (mSessionUri != null) { final Intent parentIntent = new Intent(Intent.ACTION_VIEW, mSessionUri); NavUtils.navigateUpTo(this, parentIntent); } else { finish(); } } /** * Updates the layout based on the provided configuration */ private void updateLayout(Configuration config) { if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) { if (mIsTablet) { layoutTabletForLandscape(); } else { layoutPhoneForLandscape(); } } else { if (mIsTablet) { layoutTabletForPortrait(); } else { layoutPhoneForPortrait(); } } } private void layoutPhoneForLandscape() { layoutFullscreenVideo(true); } private void layoutPhoneForPortrait() { layoutFullscreenVideo(false); SessionSummaryFragment fragment = (SessionSummaryFragment) mTabsAdapter.mFragments.get(TABNUM_SESSION_SUMMARY); if (fragment != null) { fragment.updateViews(); } } private void layoutTabletForLandscape() { mMainLayout.setOrientation(LinearLayout.HORIZONTAL); final LayoutParams videoLayoutParams = (LayoutParams) mVideoLayout.getLayoutParams(); videoLayoutParams.height = LayoutParams.MATCH_PARENT; videoLayoutParams.width = 0; videoLayoutParams.weight = 1; mVideoLayout.setLayoutParams(videoLayoutParams); final LayoutParams extraLayoutParams = (LayoutParams) mExtraLayout.getLayoutParams(); extraLayoutParams.height = LayoutParams.MATCH_PARENT; extraLayoutParams.width = 0; extraLayoutParams.weight = 1; mExtraLayout.setLayoutParams(extraLayoutParams); } private void layoutTabletForPortrait() { mMainLayout.setOrientation(LinearLayout.VERTICAL); final LayoutParams videoLayoutParams = (LayoutParams) mVideoLayout.getLayoutParams(); videoLayoutParams.width = LayoutParams.MATCH_PARENT; if (mLoadFromExtras) { // Loading from extras, let the top fragment wrap_content videoLayoutParams.height = LayoutParams.WRAP_CONTENT; videoLayoutParams.weight = 0; } else { // Otherwise the session description will be longer, give it some space videoLayoutParams.height = 0; videoLayoutParams.weight = 7; } mVideoLayout.setLayoutParams(videoLayoutParams); final LayoutParams extraLayoutParams = (LayoutParams) mExtraLayout.getLayoutParams(); extraLayoutParams.width = LayoutParams.MATCH_PARENT; extraLayoutParams.height = 0; extraLayoutParams.weight = 5; mExtraLayout.setLayoutParams(extraLayoutParams); } private void layoutFullscreenVideo(boolean fullscreen) { if (mIsFullscreen != fullscreen) { mIsFullscreen = fullscreen; if (mIsTablet) { // Tablet specific full screen layout layoutTabletFullScreen(fullscreen); } else { // Phone specific full screen layout layoutPhoneFullScreen(fullscreen); } // Full screen layout changes for all form factors final LayoutParams params = (LayoutParams) mPlayerContainer.getLayoutParams(); if (fullscreen) { if (mCaptionsMenuItem != null) { mCaptionsMenuItem.setVisible(true); } params.height = LayoutParams.MATCH_PARENT; mMainLayout.setPadding(0, 0, 0, 0); } else { getSupportActionBar().show(); if (mCaptionsMenuItem != null) { mCaptionsMenuItem.setVisible(false); } mFullscreenCaptions.setVisibility(View.GONE); params.height = LayoutParams.WRAP_CONTENT; adjustMainLayoutForActionBar(); } View youTubePlayerView = mYouTubePlayer.getView(); if (youTubePlayerView != null) { ViewGroup.LayoutParams playerParams = mYouTubePlayer.getView().getLayoutParams(); playerParams.height = fullscreen ? LayoutParams.MATCH_PARENT : LayoutParams.WRAP_CONTENT; youTubePlayerView.setLayoutParams(playerParams); } mPlayerContainer.setLayoutParams(params); } } private void adjustMainLayoutForActionBar() { if (UIUtils.hasICS()) { // On ICS+ we use FEATURE_ACTION_BAR_OVERLAY so full screen mode doesn't need to // re-adjust layouts when hiding action bar. To account for this we add action bar // height pack to the padding when not in full screen mode. mMainLayout.setPadding(0, getActionBarHeightPx(), 0, 0); } } /** * Adjusts tablet layouts for full screen video. * * @param fullscreen True to layout in full screen, false to switch to regular layout */ private void layoutTabletFullScreen(boolean fullscreen) { if (fullscreen) { mExtraLayout.setVisibility(View.GONE); mSummaryLayout.setVisibility(View.GONE); mVideoLayout.setPadding(0, 0, 0, 0); final LayoutParams videoLayoutParams = (LayoutParams) mVideoLayout.getLayoutParams(); videoLayoutParams.setMargins(0, 0, 0, 0); mVideoLayout.setLayoutParams(videoLayoutParams); } else { final int padding = getResources().getDimensionPixelSize(R.dimen.multipane_half_padding); mExtraLayout.setVisibility(View.VISIBLE); mSummaryLayout.setVisibility(View.VISIBLE); mVideoLayout.setBackgroundResource(R.drawable.grey_frame_on_white); final LayoutParams videoLayoutParams = (LayoutParams) mVideoLayout.getLayoutParams(); videoLayoutParams.setMargins(padding, padding, padding, padding); mVideoLayout.setLayoutParams(videoLayoutParams); } } /** * Adjusts phone layouts for full screen video. */ private void layoutPhoneFullScreen(boolean fullscreen) { if (fullscreen) { mTabHost.setVisibility(View.GONE); } else { mTabHost.setVisibility(View.VISIBLE); } } private int getActionBarHeightPx() { int[] attrs = new int[] { android.R.attr.actionBarSize }; return (int) getTheme().obtainStyledAttributes(attrs).getDimension(0, 0f); } /** * Adapter that backs the action bar drop-down spinner. */ private class LivestreamAdapter extends CursorAdapter { LayoutInflater mLayoutInflater; public LivestreamAdapter(Context context) { super(context, null, false); if (UIUtils.hasICS()) { mLayoutInflater = (LayoutInflater) getSupportActionBar().getThemedContext() .getSystemService(LAYOUT_INFLATER_SERVICE); } else { mLayoutInflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE); } } @Override public Object getItem(int position) { mCursor.moveToPosition(position); return mCursor; } @Override public View newDropDownView(Context context, Cursor cursor, ViewGroup parent) { // Inflate view that appears in the drop-down spinner views return mLayoutInflater.inflate( R.layout.spinner_item_session_livestream, parent, false); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { // Inflate view that appears in the selected spinner return mLayoutInflater.inflate(android.R.layout.simple_spinner_item, parent, false); } @Override public void bindView(View view, Context context, Cursor cursor) { // Bind view that appears in the selected spinner or in the drop-down final TextView titleView = (TextView) view.findViewById(android.R.id.text1); final TextView subTitleView = (TextView) view.findViewById(android.R.id.text2); String trackName = cursor.getString(SessionsQuery.TRACK_NAME); if (TextUtils.isEmpty(trackName)) { trackName = getString(R.string.app_name); } else { trackName = getString(R.string.session_livestream_track_title, trackName); } String sessionTitle = cursor.getString(SessionsQuery.TITLE); if (subTitleView != null) { // Drop-down view titleView.setText(trackName); subTitleView.setText(sessionTitle); } else { // Selected view titleView.setText(getString(R.string.session_livestream_title) + ": " + trackName); } } } /** * Adapter that backs the viewpager tabs on the phone UI. */ private static class TabsAdapter extends FragmentPagerAdapter implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener { private final FragmentActivity mContext; private final TabHost mTabHost; private final ViewPager mViewPager; public final SparseArray<Fragment> mFragments; private final ArrayList<Integer> mTabNums; private int mTabCount = 0; static class DummyTabFactory implements TabHost.TabContentFactory { private final Context mContext; public DummyTabFactory(Context context) { mContext = context; } @Override public View createTabContent(String tag) { View v = new View(mContext); v.setMinimumWidth(0); v.setMinimumHeight(0); return v; } } public TabsAdapter(FragmentActivity activity, TabHost tabHost, ViewPager pager) { super(activity.getSupportFragmentManager()); mContext = activity; mTabHost = tabHost; mViewPager = pager; mTabHost.setOnTabChangedListener(this); mViewPager.setAdapter(this); mViewPager.setOnPageChangeListener(this); mFragments = new SparseArray<Fragment>(3); mTabNums = new ArrayList<Integer>(3); } public void addTab(String tabTitle, Fragment newFragment, int tabId) { ViewGroup tabWidget = (ViewGroup) mTabHost.findViewById(android.R.id.tabs); TextView tabIndicatorView = (TextView) mContext.getLayoutInflater().inflate( R.layout.tab_indicator_color, tabWidget, false); tabIndicatorView.setText(tabTitle); final TabHost.TabSpec tabSpec = mTabHost.newTabSpec(String.valueOf(mTabCount++)); tabSpec.setIndicator(tabIndicatorView); tabSpec.setContent(new DummyTabFactory(mContext)); mTabHost.addTab(tabSpec); mFragments.put(tabId, newFragment); mTabNums.add(tabId); notifyDataSetChanged(); } @Override public int getCount() { return mFragments.size(); } @Override public Fragment getItem(int position) { return mFragments.get(mTabNums.get(position)); } @Override public void onTabChanged(String tabId) { int position = mTabHost.getCurrentTab(); mViewPager.setCurrentItem(position); } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { // Unfortunately when TabHost changes the current tab, it kindly also takes care of // putting focus on it when not in touch mode. The jerk. This hack tries to prevent // this from pulling focus out of our ViewPager. TabWidget widget = mTabHost.getTabWidget(); int oldFocusability = widget.getDescendantFocusability(); widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS); mTabHost.setCurrentTab(position); widget.setDescendantFocusability(oldFocusability); } @Override public void onPageScrollStateChanged(int state) { } } /** * Simple fragment that inflates a session summary layout that displays session title and * abstract. */ public static class SessionSummaryFragment extends Fragment { private TextView mTitleView; private TextView mAbstractView; private String mTitle; private String mAbstract; public SessionSummaryFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_session_summary, null); mTitleView = (TextView) view.findViewById(R.id.session_title); mAbstractView = (TextView) view.findViewById(R.id.session_abstract); updateViews(); return view; } public void setSessionSummaryInfo(String sessionTitle, String sessionAbstract) { mTitle = sessionTitle; mAbstract = sessionAbstract; updateViews(); } public void updateViews() { if (mTitleView != null && mAbstractView != null) { mTitleView.setText(mTitle); if (!TextUtils.isEmpty(mAbstract)) { mAbstractView.setVisibility(View.VISIBLE); mAbstractView.setText(mAbstract); } else { mAbstractView.setVisibility(View.GONE); } } } } /** * Simple fragment that shows the live captions. */ public static class SessionLiveCaptionsFragment extends Fragment { private static final String CAPTIONS_DARK_THEME_URL_PARAM = "&theme=dark"; private FrameLayout mContainer; private WebView mWebView; private TextView mNoCaptionsTextView; private boolean mDarkTheme = false; private String mSessionTrack; public SessionLiveCaptionsFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_session_captions, null); mContainer = (FrameLayout) view.findViewById(R.id.session_caption_container); mNoCaptionsTextView = (TextView) view.findViewById(android.R.id.empty); mWebView = (WebView) view.findViewById(R.id.session_caption_area); mWebView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { // Disable text selection in WebView (doesn't work well with the YT player // triggering full screen chrome after a timeout) return true; } }); mWebView.setWebViewClient(new WebViewClient() { @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { showNoCaptionsAvailable(); } }); updateViews(); return view; } public void setTrackName(String sessionTrack) { mSessionTrack = sessionTrack; updateViews(); } public void setDarkTheme(boolean dark) { mDarkTheme = dark; } public void updateViews() { if (mWebView != null && !TextUtils.isEmpty(mSessionTrack)) { if (mDarkTheme) { mWebView.setBackgroundColor(Color.BLACK); mContainer.setBackgroundColor(Color.BLACK); mNoCaptionsTextView.setTextColor(Color.WHITE); } else { mWebView.setBackgroundColor(Color.WHITE); mContainer.setBackgroundColor(Color.WHITE); } String captionsUrl; final String trackLowerCase = mSessionTrack.toLowerCase(); if (mSessionTrack.equals(KEYNOTE_TRACK_NAME)|| trackLowerCase.equals(Config.PRIMARY_LIVESTREAM_TRACK)) { // if keynote or primary track, use primary captions url captionsUrl = Config.PRIMARY_LIVESTREAM_CAPTIONS_URL; } else if (trackLowerCase.equals(Config.SECONDARY_LIVESTREAM_TRACK)) { // else if secondary track use secondary captions url captionsUrl = Config.SECONDARY_LIVESTREAM_CAPTIONS_URL; } else { // otherwise we don't have captions captionsUrl = null; } if (captionsUrl != null) { if (mDarkTheme) { captionsUrl += CAPTIONS_DARK_THEME_URL_PARAM; } mWebView.getSettings().setJavaScriptEnabled(true); mWebView.loadUrl(captionsUrl); mNoCaptionsTextView.setVisibility(View.GONE); mWebView.setVisibility(View.VISIBLE); } else { showNoCaptionsAvailable(); } } } private void showNoCaptionsAvailable() { mWebView.setVisibility(View.GONE); mNoCaptionsTextView.setVisibility(View.VISIBLE); } } private static class SessionShareData { String SESSION_TITLE; String SESSION_HASHTAG; String SESSION_URL; public SessionShareData(String title, String hashTag, String url) { SESSION_TITLE = title; SESSION_HASHTAG = hashTag; SESSION_URL = url; } } /** * Single session query */ public interface SessionSummaryQuery { int _TOKEN = 0; String[] PROJECTION = { ScheduleContract.Sessions.SESSION_ID, ScheduleContract.Sessions.SESSION_TITLE, ScheduleContract.Sessions.SESSION_ABSTRACT, ScheduleContract.Sessions.SESSION_HASHTAGS, ScheduleContract.Sessions.SESSION_LIVESTREAM_URL, Tracks.TRACK_NAME, ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_END, }; int SESSION_ID = 0; int TITLE = 1; int ABSTRACT = 2; int HASHTAGS = 3; int LIVESTREAM_URL = 4; int TRACK_NAME = 5; int BLOCK_START= 6; int BLOCK_END = 7; } /** * List of sessions query */ public interface SessionsQuery { int _TOKEN = 1; String[] PROJECTION = { BaseColumns._ID, Sessions.SESSION_ID, Sessions.SESSION_TITLE, Tracks.TRACK_NAME, Tracks.TRACK_COLOR, ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_END, }; int ID = 0; int SESSION_ID = 1; int TITLE = 2; int TRACK_NAME = 3; int TRACK_COLOR = 4; int BLOCK_START= 5; int BLOCK_END = 6; } }
1162584980-google-io
android/src/com/google/android/apps/iosched/ui/SessionLivestreamActivity.java
Java
asf20
47,101
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.util.BeamUtils; import com.google.android.apps.iosched.util.ReflectionUtils; import com.google.android.apps.iosched.util.UIUtils; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import android.annotation.TargetApi; import android.app.AlertDialog; import android.app.SearchManager; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.nfc.NfcAdapter; import android.nfc.NfcEvent; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.text.Html; import android.widget.SearchView; import static com.google.android.apps.iosched.util.LogUtils.LOGD; /** * An activity that shows session search results. This activity can be either single * or multi-pane, depending on the device configuration. */ public class SearchActivity extends BaseActivity implements SessionsFragment.Callbacks { private boolean mTwoPane; private SessionsFragment mSessionsFragment; private Fragment mDetailFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search); mTwoPane = (findViewById(R.id.fragment_container_detail) != null); FragmentManager fm = getSupportFragmentManager(); mSessionsFragment = (SessionsFragment) fm.findFragmentById(R.id.fragment_container_master); if (mSessionsFragment == null) { mSessionsFragment = new SessionsFragment(); fm.beginTransaction() .add(R.id.fragment_container_master, mSessionsFragment) .commit(); } mDetailFragment = fm.findFragmentById(R.id.fragment_container_detail); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); onNewIntent(getIntent()); } @Override public void onNewIntent(Intent intent) { setIntent(intent); String query = intent.getStringExtra(SearchManager.QUERY); setTitle(Html.fromHtml(getString(R.string.title_search_query, query))); mSessionsFragment.reloadFromArguments(intentToFragmentArguments( new Intent(Intent.ACTION_VIEW, Sessions.buildSearchUri(query)))); EasyTracker.getTracker().trackView("Search: " + query); LOGD("Tracker", "Search: " + query); updateDetailBackground(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getSupportMenuInflater().inflate(R.menu.search, menu); setupSearchMenuItem(menu); return true; } @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void setupSearchMenuItem(Menu menu) { final MenuItem searchItem = menu.findItem(R.id.menu_search); if (searchItem != null && UIUtils.hasHoneycomb()) { SearchView searchView = (SearchView) searchItem.getActionView(); if (searchView != null) { SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE); searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String s) { ReflectionUtils.tryInvoke(searchItem, "collapseActionView"); return false; } @Override public boolean onQueryTextChange(String s) { return false; } }); searchView.setOnSuggestionListener(new SearchView.OnSuggestionListener() { @Override public boolean onSuggestionSelect(int i) { return false; } @Override public boolean onSuggestionClick(int i) { ReflectionUtils.tryInvoke(searchItem, "collapseActionView"); return false; } }); } } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_search: if (!UIUtils.hasHoneycomb()) { startSearch(null, false, Bundle.EMPTY, false); return true; } break; } return super.onOptionsItemSelected(item); } private void updateDetailBackground() { if (mTwoPane) { findViewById(R.id.fragment_container_detail).setBackgroundResource( (mDetailFragment == null) ? R.drawable.grey_frame_on_white_empty_sessions : R.drawable.grey_frame_on_white); } } @Override public boolean onSessionSelected(String sessionId) { Uri sessionUri = ScheduleContract.Sessions.buildSessionUri(sessionId); Intent detailIntent = new Intent(Intent.ACTION_VIEW, sessionUri); if (mTwoPane) { BeamUtils.setBeamSessionUri(this, sessionUri); trySetBeamCallback(); SessionDetailFragment fragment = new SessionDetailFragment(); fragment.setArguments(BaseActivity.intentToFragmentArguments(detailIntent)); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container_detail, fragment) .commit(); mDetailFragment = fragment; updateDetailBackground(); return true; } else { startActivity(detailIntent); return false; } } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) private void trySetBeamCallback() { if (UIUtils.hasICS()) { BeamUtils.setBeamCompleteCallback(this, new NfcAdapter.OnNdefPushCompleteCallback() { @Override public void onNdefPushComplete(NfcEvent event) { // Beam has been sent if (!BeamUtils.isBeamUnlocked(SearchActivity.this)) { BeamUtils.setBeamUnlocked(SearchActivity.this); runOnUiThread(new Runnable() { @Override public void run() { showFirstBeamDialog(); } }); } } }); } } private void showFirstBeamDialog() { new AlertDialog.Builder(this) .setTitle(R.string.just_beamed) .setMessage(R.string.beam_unlocked_session) .setNegativeButton(R.string.close, null) .setPositiveButton(R.string.view_beam_session, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { BeamUtils.launchBeamSession(SearchActivity.this); di.dismiss(); } }) .create() .show(); } }
1162584980-google-io
android/src/com/google/android/apps/iosched/ui/SearchActivity.java
Java
asf20
8,467
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.youtube.api; import android.content.Context; /** * Temporarily just a stub. */ public class YouTube { public static void initialize(Context context, String key) { } }
1162584980-google-io
android/src/com/google/android/youtube/api/YouTube.java
Java
asf20
803
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.youtube.api; /** * Temporarily just a stub. */ public interface YouTubePlayer { public static int FULLSCREEN_FLAG_CONTROL_ORIENTATION = 1; public static int FULLSCREEN_FLAG_CONTROL_SYSTEM_UI = 2; public static int FULLSCREEN_FLAG_FULLSCREEN_WHEN_DEVICE_LANDSCAPE = 4; public void cueVideo(java.lang.String s); public void loadVideo(java.lang.String s); public void cuePlaylist(java.lang.String s); public void loadPlaylist(java.lang.String s); public void cueVideos(java.util.List<java.lang.String> strings); public void loadVideos(java.util.List<java.lang.String> strings); public void play(); public void pause(); public void release(); public boolean hasNext(); public boolean hasPrevious(); public void next(); public void previous(); public int getCurrentTimeMillis(); public void seekToMillis(int i); public void seekRelativeMillis(int i); public void setFullscreen(boolean b); public void enableCustomFullscreen(com.google.android.youtube.api.YouTubePlayer.OnFullscreenListener onFullscreenListener); public void setFullscreenControlFlags(int i); public void setShowControls(boolean b); public void setManageAudioFocus(boolean b); public void setOnPlaybackEventsListener(com.google.android.youtube.api.YouTubePlayer.OnPlaybackEventsListener onPlaybackEventsListener); public void setUseSurfaceTexture(boolean b); public static interface OnFullscreenListener { void onFullscreen(boolean b); } public static interface OnPlaybackEventsListener { void onLoaded(java.lang.String s); void onPlaying(); void onPaused(); void onBuffering(boolean b); void onEnded(); void onError(); } }
1162584980-google-io
android/src/com/google/android/youtube/api/YouTubePlayer.java
Java
asf20
2,419
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.youtube.api; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.List; /** * Temporarily just a stub. */ public class YouTubePlayerSupportFragment extends Fragment implements YouTubePlayer { public YouTubePlayerSupportFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = new View(getActivity()); v.setBackgroundColor(0); return v; } @Override public void cueVideo(String s) { } @Override public void loadVideo(String s) { } @Override public void cuePlaylist(String s) { } @Override public void loadPlaylist(String s) { } @Override public void cueVideos(List<String> strings) { } @Override public void loadVideos(List<String> strings) { } @Override public void play() { } @Override public void pause() { } @Override public void release() { } @Override public boolean hasNext() { return false; } @Override public boolean hasPrevious() { return false; } @Override public void next() { } @Override public void previous() { } @Override public int getCurrentTimeMillis() { return 0; } @Override public void seekToMillis(int i) { } @Override public void seekRelativeMillis(int i) { } @Override public void setFullscreen(boolean b) { } @Override public void enableCustomFullscreen(OnFullscreenListener onFullscreenListener) { } @Override public void setFullscreenControlFlags(int i) { } @Override public void setShowControls(boolean b) { } @Override public void setManageAudioFocus(boolean b) { } @Override public void setOnPlaybackEventsListener(OnPlaybackEventsListener onPlaybackEventsListener) { } @Override public void setUseSurfaceTexture(boolean b) { } }
1162584980-google-io
android/src/com/google/android/youtube/api/YouTubePlayerSupportFragment.java
Java
asf20
2,768
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.analytics.tracking.android; import android.app.Activity; import android.content.Context; /** * Temporarily just a stub. */ public class EasyTracker { public static EasyTracker getTracker() { return new EasyTracker(); } public void trackView(String s) { } public void trackActivityStart(Activity activity) { } public void trackActivityStop(Activity activity) { } public void setContext(Context context) { } public void trackEvent(String s1, String s2, String s3, long l) { } public void dispatch() { } }
1162584980-google-io
android/src/com/google/analytics/tracking/android/EasyTracker.java
Java
asf20
1,193
#!/bin/sh if [[ -z $ADB ]]; then ADB=adb; fi ./kill_process.sh $ADB shell rm -r /data/data/com.google.android.apps.iosched/*
1162584980-google-io
scripts/kill_data.sh
Shell
asf20
124
#!/bin/sh adb shell cat /data/data/com.google.android.apps.iosched/shared_prefs/com.google.android.apps.iosched_preferences.xml | xmllint --format -
1162584980-google-io
scripts/cat_preferences.sh
Shell
asf20
148
#!/bin/sh if [[ -z $ADB ]]; then ADB=adb; fi $ADB shell am start \ -a android.intent.action.MAIN \ -c android.intent.category.LAUNCHER \ -n com.google.android.apps.iosched/.ui.HomeActivity
1162584980-google-io
scripts/launch.sh
Shell
asf20
202
#!/bin/sh adb shell pm clear com.google.android.apps.iosched
1162584980-google-io
scripts/cleardata.sh
Shell
asf20
60
#!/bin/sh if [[ -z $ADB ]]; then ADB=adb; fi $ADB shell am force-stop com.google.android.apps.iosched
1162584980-google-io
scripts/kill_process.sh
Shell
asf20
102
#!/bin/sh if [[ -z $ADB ]]; then ADB=adb; fi MAC_UNAME="Darwin" if [[ "`uname`" == ${MAC_UNAME} ]]; then DATE_FORMAT="%Y-%m-%dT%H:%M:%S" else DATE_FORMAT="%Y-%m-%d %H:%M:%S" fi if [ -z "$1" ]; then NOW_DATE=$(date "+${DATE_FORMAT}") echo Please provide a mock time in the format \"${NOW_DATE}\" or \"d\" to delete the mock time. >&2 exit fi TEMP_FILE=$(mktemp -t iosched_mock_time.XXXXXXXX) MOCK_TIME_STR="$1" if [[ "d" == "${MOCK_TIME_STR}" ]]; then echo Deleting mock time... >&2 ./kill_process.sh $ADB shell rm /data/data/com.google.android.apps.iosched/shared_prefs/mock_data.xml exit fi if [[ "`uname`" == ${MAC_UNAME} ]]; then MOCK_TIME_MSEC=$(date -j -f ${DATE_FORMAT} ${MOCK_TIME_STR} "+%s")000 else MOCK_TIME_MSEC=$(date -d "${MOCK_TIME_STR}" +%s)000 fi echo Setting mock time to "${MOCK_TIME_STR}" == "${MOCK_TIME_MSEC}" ... >&2 cat >${TEMP_FILE}<<EOT <?xml version='1.0' encoding='utf-8' standalone='yes' ?> <map> <long name="mock_current_time" value="${MOCK_TIME_MSEC}"/> </map> EOT ./kill_process.sh $ADB push ${TEMP_FILE} /data/data/com.google.android.apps.iosched/shared_prefs/mock_data.xml
1162584980-google-io
scripts/set_mock_time.sh
Shell
asf20
1,137
#!/usr/bin/python # Copyright 2011 Google, Inc. All Rights Reserved. # simple script to walk source tree looking for third-party licenses # dumps resulting html page to stdout import os, re, mimetypes, sys # read source directories to scan from command line SOURCE = sys.argv[1:] # regex to find /* */ style comment blocks COMMENT_BLOCK = re.compile(r"(/\*.+?\*/)", re.MULTILINE | re.DOTALL) # regex used to detect if comment block is a license COMMENT_LICENSE = re.compile(r"(license)", re.IGNORECASE) COMMENT_COPYRIGHT = re.compile(r"(copyright)", re.IGNORECASE) EXCLUDE_TYPES = [ "application/xml", "image/png", ] # list of known licenses; keys are derived by stripping all whitespace and # forcing to lowercase to help combine multiple files that have same license. KNOWN_LICENSES = {} class License: def __init__(self, license_text): self.license_text = license_text self.filenames = [] # add filename to the list of files that have the same license text def add_file(self, filename): if filename not in self.filenames: self.filenames.append(filename) LICENSE_KEY = re.compile(r"[^\w]") def find_license(license_text): # TODO(alice): a lot these licenses are almost identical Apache licenses. # Most of them differ in origin/modifications. Consider combining similar # licenses. license_key = LICENSE_KEY.sub("", license_text).lower() if license_key not in KNOWN_LICENSES: KNOWN_LICENSES[license_key] = License(license_text) return KNOWN_LICENSES[license_key] def discover_license(exact_path, filename): # when filename ends with LICENSE, assume applies to filename prefixed if filename.endswith("LICENSE"): with open(exact_path) as file: license_text = file.read() target_filename = filename[:-len("LICENSE")] if target_filename.endswith("."): target_filename = target_filename[:-1] find_license(license_text).add_file(target_filename) return None # try searching for license blocks in raw file mimetype = mimetypes.guess_type(filename) if mimetype in EXCLUDE_TYPES: return None with open(exact_path) as file: raw_file = file.read() # include comments that have both "license" and "copyright" in the text for comment in COMMENT_BLOCK.finditer(raw_file): comment = comment.group(1) if COMMENT_LICENSE.search(comment) is None: continue if COMMENT_COPYRIGHT.search(comment) is None: continue find_license(comment).add_file(filename) for source in SOURCE: for root, dirs, files in os.walk(source): for name in files: discover_license(os.path.join(root, name), name) print "<html><head><style> body { font-family: sans-serif; } pre { background-color: #eeeeee; padding: 1em; white-space: pre-wrap; } </style></head><body>" for license in KNOWN_LICENSES.values(): print "<h3>Notices for files:</h3><ul>" filenames = license.filenames filenames.sort() for filename in filenames: print "<li>%s</li>" % (filename) print "</ul>" print "<pre>%s</pre>" % license.license_text print "</body></html>"
1162584980-google-io
scripts/collect_licenses.py
Python
asf20
3,190
#!/bin/sh # Remember VERBOSE only works on debug builds of the app adb shell setprop log.tag.iosched_SyncHelper VERBOSE adb shell setprop log.tag.iosched_SessionsHandler VERBOSE adb shell setprop log.tag.iosched_ImageCache VERBOSE adb shell setprop log.tag.iosched_ImageWorker VERBOSE adb shell setprop log.tag.iosched_ImageFetcher VERBOSE
1162584980-google-io
scripts/increase_verbosity.sh
Shell
asf20
339
#!/bin/sh if [[ -z $ADB ]]; then ADB=adb; fi $ADB shell "echo '$*' | sqlite3 -header -column /data/data/com.google.android.apps.iosched/databases/schedule.db"
1162584980-google-io
scripts/dbquery.sh
Shell
asf20
158
#!/bin/sh # Sessions list #adb shell am start -a android.intent.action.VIEW -d content://com.google.android.apps.iosched/tracks/android/sessions # Vendors list #adb shell am start -a android.intent.action.VIEW -d content://com.google.android.apps.iosched/tracks/android/vendors # Session detail #adb shell am start -a android.intent.action.VIEW -d content://com.google.android.apps.iosched/sessions/honeycombhighlights # Vendor detail #adb shell am start -a android.intent.action.VIEW -d content://com.google.android.apps.iosched/vendors/bestbuy # Track details #adb shell am start -a android.intent.action.VIEW -d content://com.google.android.apps.iosched/tracks/chrome
1162584980-google-io
scripts/deeplinks.sh
Shell
asf20
676
<html> <body> <h2>Push request could not be queued!</h2> </body> </html>
1162584980-google-io
gcm-server/war/error.html
HTML
asf20
72
<html> <body> <h2>Push request queued successfully!</h2> </body> </html>
1162584980-google-io
gcm-server/war/success.html
HTML
asf20
72
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.gcm.server; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.appengine.api.datastore.FetchOptions; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.datastore.PreparedQuery; import com.google.appengine.api.datastore.Query; import com.google.appengine.api.datastore.Query.FilterOperator; import com.google.appengine.api.datastore.Transaction; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; /** * Simple implementation of a data store using standard Java collections. This class is neither * persistent (it will lost the data when the app is restarted) nor thread safe. */ public final class Datastore { private static final Logger logger = Logger.getLogger(Datastore.class.getSimpleName()); static final String MULTICAST_TYPE = "Multicast"; static final String MULTICAST_REG_IDS_PROPERTY = "regIds"; static final String MULTICAST_ANNOUNCEMENT_PROPERTY = "announcement"; static final int MULTICAST_SIZE = 1000; static final String DEVICE_TYPE = "Device"; static final String DEVICE_REG_ID_PROPERTY = "regid"; private static final FetchOptions DEFAULT_FETCH_OPTIONS = FetchOptions.Builder .withPrefetchSize(MULTICAST_SIZE) .chunkSize(MULTICAST_SIZE); private static final DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); private Datastore() { throw new UnsupportedOperationException(); } /** * Registers a device. */ public static void register(String regId) { logger.info("Registering " + regId); Transaction txn = ds.beginTransaction(); try { Entity entity = findDeviceByRegId(regId); if (entity != null) { logger.fine(regId + " is already registered; ignoring."); return; } entity = new Entity(DEVICE_TYPE); entity.setProperty(DEVICE_REG_ID_PROPERTY, regId); ds.put(entity); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Unregisters a device. */ public static void unregister(String regId) { logger.info("Unregistering " + regId); Transaction txn = ds.beginTransaction(); try { Entity entity = findDeviceByRegId(regId); if (entity == null) { logger.warning("Device " + regId + " already unregistered"); } else { Key key = entity.getKey(); ds.delete(key); } txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Updates the registration id of a device. */ public static void updateRegistration(String oldId, String newId) { logger.info("Updating " + oldId + " to " + newId); Transaction txn = ds.beginTransaction(); try { Entity entity = findDeviceByRegId(oldId); if (entity == null) { logger.warning("No device for registration id " + oldId); return; } entity.setProperty(DEVICE_REG_ID_PROPERTY, newId); ds.put(entity); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Gets the number of total devices. */ public static int getTotalDevices() { Transaction txn = ds.beginTransaction(); try { Query query = new Query(DEVICE_TYPE).setKeysOnly(); List<Entity> allKeys = ds.prepare(query).asList(DEFAULT_FETCH_OPTIONS); int total = allKeys.size(); logger.fine("Total number of devices: " + total); txn.commit(); return total; } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Gets all registered devices. */ public static List<String> getDevices() { List<String> devices; Transaction txn = ds.beginTransaction(); try { Query query = new Query(DEVICE_TYPE); Iterable<Entity> entities = ds.prepare(query).asIterable(DEFAULT_FETCH_OPTIONS); devices = new ArrayList<String>(); for (Entity entity : entities) { String device = (String) entity.getProperty(DEVICE_REG_ID_PROPERTY); devices.add(device); } txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } return devices; } /** * Returns the device object with the given registration ID. */ private static Entity findDeviceByRegId(String regId) { Query query = new Query(DEVICE_TYPE) .addFilter(DEVICE_REG_ID_PROPERTY, FilterOperator.EQUAL, regId); PreparedQuery preparedQuery = ds.prepare(query); List<Entity> entities = preparedQuery.asList(DEFAULT_FETCH_OPTIONS); Entity entity = null; if (!entities.isEmpty()) { entity = entities.get(0); } int size = entities.size(); if (size > 0) { logger.severe( "Found " + size + " entities for regId " + regId + ": " + entities); } return entity; } /** * Creates a persistent record with the devices to be notified using a multicast message. * * @param devices registration ids of the devices. * @param announcement announcement messageage * @return encoded key for the persistent record. */ public static String createMulticast(List<String> devices, String announcement) { String type = (announcement == null || announcement.trim().length() == 0) ? "sync" : ("announcement: " + announcement); logger.info("Storing multicast (" + type + ") for " + devices.size() + " devices"); String encodedKey; Transaction txn = ds.beginTransaction(); try { Entity entity = new Entity(MULTICAST_TYPE); entity.setProperty(MULTICAST_REG_IDS_PROPERTY, devices); entity.setProperty(MULTICAST_ANNOUNCEMENT_PROPERTY, announcement); ds.put(entity); Key key = entity.getKey(); encodedKey = KeyFactory.keyToString(key); logger.fine("multicast key: " + encodedKey); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } return encodedKey; } /** * Gets a persistent record with the devices to be notified using a multicast message. * * @param encodedKey encoded key for the persistent record. */ public static Entity getMulticast(String encodedKey) { Key key = KeyFactory.stringToKey(encodedKey); Entity entity; Transaction txn = ds.beginTransaction(); try { entity = ds.get(key); txn.commit(); return entity; } catch (EntityNotFoundException e) { logger.severe("No entity for key " + key); return null; } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Updates a persistent record with the devices to be notified using a multicast message. * * @param encodedKey encoded key for the persistent record. * @param devices new list of registration ids of the devices. */ public static void updateMulticast(String encodedKey, List<String> devices) { Key key = KeyFactory.stringToKey(encodedKey); Entity entity; Transaction txn = ds.beginTransaction(); try { try { entity = ds.get(key); } catch (EntityNotFoundException e) { logger.severe("No entity for key " + key); return; } entity.setProperty(MULTICAST_REG_IDS_PROPERTY, devices); ds.put(entity); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Deletes a persistent record with the devices to be notified using a multicast message. * * @param encodedKey encoded key for the persistent record. */ public static void deleteMulticast(String encodedKey) { Transaction txn = ds.beginTransaction(); try { Key key = KeyFactory.stringToKey(encodedKey); ds.delete(key); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } }
1162584980-google-io
gcm-server/src/com/google/android/apps/iosched/gcm/server/Datastore.java
Java
asf20
9,856
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.gcm.server; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that unregisters a device, whose registration id is identified by {@link * #PARAMETER_REG_ID}. The client app should call this servlet every time it receives a {@code * com.google.android.c2dm.intent.REGISTRATION} with an {@code unregistered} extra. */ @SuppressWarnings("serial") public class UnregisterServlet extends BaseServlet { private static final String PARAMETER_REG_ID = "regId"; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String regId = getParameter(req, PARAMETER_REG_ID); Datastore.unregister(regId); setSuccess(resp); } }
1162584980-google-io
gcm-server/src/com/google/android/apps/iosched/gcm/server/UnregisterServlet.java
Java
asf20
1,455
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.gcm.server; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * A servlet that shows a simple admin console for sending multicast messages. This servlet is * visible to administrators only. */ public class AdminServlet extends BaseServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.print("<html><body>"); out.print("<head><title>IOSched GCM Server</title>"); out.print("</head>"); String status = (String) req.getAttribute("status"); if (status != null) { out.print(status); } out.print("</body></html>"); int total = Datastore.getTotalDevices(); out.print("<h2>" + total + " device(s) registered!</h2>"); out.print("<form method='POST' action='/sendall'>"); out.print("<table>"); out.print("<tr>"); out.print("<td>Announcement:</td>"); out.print("<td><input type='text' name='announcement' size='80'/></td>"); out.print("</tr>"); out.print("</table>"); out.print("<br/>"); out.print("<input type='submit' value='Send Message' />"); out.print("</form>"); resp.addHeader("X-FRAME-OPTIONS", "DENY"); resp.setStatus(HttpServletResponse.SC_OK); } }
1162584980-google-io
gcm-server/src/com/google/android/apps/iosched/gcm/server/AdminServlet.java
Java
asf20
2,204
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.gcm.server; import com.google.appengine.api.taskqueue.Queue; import com.google.appengine.api.taskqueue.QueueFactory; import com.google.appengine.api.taskqueue.TaskOptions; import com.google.appengine.api.taskqueue.TaskOptions.Method; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * A servlet that pushes a GCM message to all registered devices. This servlet creates multicast * entities consisting of 1000 devices each, and creates tasks to send individual GCM messages to * each device in the multicast. * * This servlet must be authenticated against with an administrator's Google account, ideally a * shared role account. */ public class SendMessageToAllServlet extends BaseServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { Queue queue = QueueFactory.getQueue("MulticastMessagesQueue"); String announcement = req.getParameter("announcement"); if (announcement == null) { announcement = ""; } List<String> devices = Datastore.getDevices(); // must split in chunks of 1000 devices (GCM limit) int total = devices.size(); List<String> partialDevices = new ArrayList<String>(total); int counter = 0; for (String device : devices) { counter++; partialDevices.add(device); int partialSize = partialDevices.size(); if (partialSize == Datastore.MULTICAST_SIZE || counter == total) { String multicastKey = Datastore.createMulticast(partialDevices, announcement); logger.fine("Queuing " + partialSize + " devices on multicast " + multicastKey); TaskOptions taskOptions = TaskOptions.Builder .withUrl("/send") .param("multicastKey", multicastKey) .method(Method.POST); queue.add(taskOptions); partialDevices.clear(); } } logger.fine("Queued message to " + counter + " devices"); resp.sendRedirect("/success.html"); } }
1162584980-google-io
gcm-server/src/com/google/android/apps/iosched/gcm/server/SendMessageToAllServlet.java
Java
asf20
3,029
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.gcm.server; import java.util.Enumeration; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Skeleton class for all servlets in this package. */ abstract class BaseServlet extends HttpServlet { protected final Logger logger = Logger.getLogger(getClass().getSimpleName()); protected String getParameter(HttpServletRequest req, String parameter) throws ServletException { String value = req.getParameter(parameter); if (value == null || value.trim().isEmpty()) { StringBuilder parameters = new StringBuilder(); @SuppressWarnings("unchecked") Enumeration<String> names = req.getParameterNames(); while (names.hasMoreElements()) { String name = names.nextElement(); String param = req.getParameter(name); parameters.append(name).append("=").append(param).append("\n"); } logger.info("parameters: " + parameters); throw new ServletException("Parameter " + parameter + " not found"); } return value.trim(); } protected void setSuccess(HttpServletResponse resp) { resp.setStatus(HttpServletResponse.SC_OK); resp.setContentType("text/plain"); resp.setContentLength(0); } }
1162584980-google-io
gcm-server/src/com/google/android/apps/iosched/gcm/server/BaseServlet.java
Java
asf20
2,087
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.gcm.server; import com.google.android.gcm.server.Constants; import com.google.android.gcm.server.Message; import com.google.android.gcm.server.MulticastResult; import com.google.android.gcm.server.Result; import com.google.android.gcm.server.Sender; import com.google.appengine.api.datastore.Entity; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet, called from an App Engine task, that sends the given message (sync or announcement) * to all devices in a given multicast group (up to 1000). */ public class SendMessageServlet extends BaseServlet { private static final int ANNOUNCEMENT_TTL = (int) TimeUnit.MINUTES.toSeconds(300); private Sender sender; @Override public void init(ServletConfig config) throws ServletException { super.init(config); sender = newSender(config); } /** * Creates the {@link Sender} based on the servlet settings. */ protected Sender newSender(ServletConfig config) { String key = (String) config.getServletContext() .getAttribute(ApiKeyInitializer.ATTRIBUTE_ACCESS_KEY); return new Sender(key); } /** * Processes the request to add a new message. */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) { String multicastKey = req.getParameter("multicastKey"); Entity multicast = Datastore.getMulticast(multicastKey); @SuppressWarnings("unchecked") List<String> devices = (List<String>) multicast.getProperty(Datastore.MULTICAST_REG_IDS_PROPERTY); String announcement = (String) multicast.getProperty(Datastore.MULTICAST_ANNOUNCEMENT_PROPERTY); // Build the GCM message Message.Builder builder = new Message.Builder() .delayWhileIdle(true); if (announcement != null && announcement.trim().length() > 0) { builder .collapseKey("announcement") .addData("announcement", announcement) .timeToLive(ANNOUNCEMENT_TTL); } else { builder .collapseKey("sync"); } Message message = builder.build(); // Send the GCM message. MulticastResult multicastResult; try { multicastResult = sender.sendNoRetry(message, devices); logger.info("Result: " + multicastResult); } catch (IOException e) { logger.log(Level.SEVERE, "Exception posting " + message, e); taskDone(resp, multicastKey); return; } // check if any registration ids must be updated if (multicastResult.getCanonicalIds() != 0) { List<Result> results = multicastResult.getResults(); for (int i = 0; i < results.size(); i++) { String canonicalRegId = results.get(i).getCanonicalRegistrationId(); if (canonicalRegId != null) { String regId = devices.get(i); Datastore.updateRegistration(regId, canonicalRegId); } } } boolean allDone = true; if (multicastResult.getFailure() != 0) { // there were failures, check if any could be retried List<Result> results = multicastResult.getResults(); List<String> retryableRegIds = new ArrayList<String>(); for (int i = 0; i < results.size(); i++) { String error = results.get(i).getErrorCodeName(); if (error != null) { String regId = devices.get(i); logger.warning("Got error (" + error + ") for regId " + regId); if (error.equals(Constants.ERROR_NOT_REGISTERED)) { // application has been removed from device - unregister it Datastore.unregister(regId); } else if (error.equals(Constants.ERROR_UNAVAILABLE)) { retryableRegIds.add(regId); } } } if (!retryableRegIds.isEmpty()) { // update task Datastore.updateMulticast(multicastKey, retryableRegIds); allDone = false; retryTask(resp); } } if (allDone) { taskDone(resp, multicastKey); } else { retryTask(resp); } } /** * Indicates to App Engine that this task should be retried. */ private void retryTask(HttpServletResponse resp) { resp.setStatus(500); } /** * Indicates to App Engine that this task is done. */ private void taskDone(HttpServletResponse resp, String multicastKey) { Datastore.deleteMulticast(multicastKey); resp.setStatus(200); } }
1162584980-google-io
gcm-server/src/com/google/android/apps/iosched/gcm/server/SendMessageServlet.java
Java
asf20
5,791
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.gcm.server; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that registers a device, whose registration id is identified by {@link * #PARAMETER_REG_ID}. * * The client app should call this servlet every time it receives a {@code * com.google.android.c2dm.intent.REGISTRATION C2DM} intent without an error or {@code unregistered} * extra. */ @SuppressWarnings("serial") public class RegisterServlet extends BaseServlet { private static final String PARAMETER_REG_ID = "regId"; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String regId = getParameter(req, PARAMETER_REG_ID); Datastore.register(regId); setSuccess(resp); } }
1162584980-google-io
gcm-server/src/com/google/android/apps/iosched/gcm/server/RegisterServlet.java
Java
asf20
1,482
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.gcm.server; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import java.util.logging.Logger; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; /** * Context initializer that loads the API key from the App Engine datastore. */ public class ApiKeyInitializer implements ServletContextListener { private final Logger logger = Logger.getLogger(ApiKeyInitializer.class.getSimpleName()); // Don't actually hard code your key here; rather, edit the entity in the App Engine console. static final String FAKE_API_KEY = "ENTER_KEY_HERE"; static final String ATTRIBUTE_ACCESS_KEY = "apiKey"; private static final String ENTITY_KIND = "Settings"; private static final String ENTITY_KEY = "MyKey"; private static final String ACCESS_KEY_FIELD = "ApiKey"; @Override public void contextInitialized(ServletContextEvent event) { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Key key = KeyFactory.createKey(ENTITY_KIND, ENTITY_KEY); Entity entity; try { entity = datastore.get(key); } catch (EntityNotFoundException e) { entity = new Entity(key); // NOTE: it's not possible to change entities in the local server, so // it will be necessary to hardcode the API key below if you are running // it locally. entity.setProperty(ACCESS_KEY_FIELD, FAKE_API_KEY); datastore.put(entity); logger.severe("Created fake key. Please go to App Engine admin " + "console, change its value to your API Key (the entity " + "type is '" + ENTITY_KIND + "' and its field to be changed is '" + ACCESS_KEY_FIELD + "'), then restart the server!"); } String accessKey = (String) entity.getProperty(ACCESS_KEY_FIELD); event.getServletContext().setAttribute(ATTRIBUTE_ACCESS_KEY, accessKey); } /** * Gets the access key. */ protected String getKey() { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Key key = KeyFactory.createKey(ENTITY_KIND, ENTITY_KEY); String apiKey = ""; try { Entity entity = datastore.get(key); apiKey = (String) entity.getProperty(ACCESS_KEY_FIELD); } catch (EntityNotFoundException e) { logger.severe("Exception while retrieving the API Key" + e.toString()); } return apiKey; } @Override public void contextDestroyed(ServletContextEvent event) { } }
1162584980-google-io
gcm-server/src/com/google/android/apps/iosched/gcm/server/ApiKeyInitializer.java
Java
asf20
3,560
package android.support.v4.app; import android.util.Log; import android.view.View; import android.view.Window; import com.actionbarsherlock.ActionBarSherlock.OnCreatePanelMenuListener; import com.actionbarsherlock.ActionBarSherlock.OnMenuItemSelectedListener; import com.actionbarsherlock.ActionBarSherlock.OnPreparePanelListener; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import java.util.ArrayList; /** I'm in ur package. Stealing ur variables. */ public abstract class _ActionBarSherlockTrojanHorse extends FragmentActivity implements OnCreatePanelMenuListener, OnPreparePanelListener, OnMenuItemSelectedListener { private static final boolean DEBUG = false; private static final String TAG = "_ActionBarSherlockTrojanHorse"; /** Fragment interface for menu creation callback. */ public interface OnCreateOptionsMenuListener { public void onCreateOptionsMenu(Menu menu, MenuInflater inflater); } /** Fragment interface for menu preparation callback. */ public interface OnPrepareOptionsMenuListener { public void onPrepareOptionsMenu(Menu menu); } /** Fragment interface for menu item selection callback. */ public interface OnOptionsItemSelectedListener { public boolean onOptionsItemSelected(MenuItem item); } private ArrayList<Fragment> mCreatedMenus; /////////////////////////////////////////////////////////////////////////// // Sherlock menu handling /////////////////////////////////////////////////////////////////////////// @Override public boolean onCreatePanelMenu(int featureId, Menu menu) { if (DEBUG) Log.d(TAG, "[onCreatePanelMenu] featureId: " + featureId + ", menu: " + menu); if (featureId == Window.FEATURE_OPTIONS_PANEL) { boolean result = onCreateOptionsMenu(menu); if (DEBUG) Log.d(TAG, "[onCreatePanelMenu] activity create result: " + result); MenuInflater inflater = getSupportMenuInflater(); boolean show = false; ArrayList<Fragment> newMenus = null; if (mFragments.mActive != null) { for (int i = 0; i < mFragments.mAdded.size(); i++) { Fragment f = mFragments.mAdded.get(i); if (f != null && !f.mHidden && f.mHasMenu && f.mMenuVisible && f instanceof OnCreateOptionsMenuListener) { show = true; ((OnCreateOptionsMenuListener)f).onCreateOptionsMenu(menu, inflater); if (newMenus == null) { newMenus = new ArrayList<Fragment>(); } newMenus.add(f); } } } if (mCreatedMenus != null) { for (int i = 0; i < mCreatedMenus.size(); i++) { Fragment f = mCreatedMenus.get(i); if (newMenus == null || !newMenus.contains(f)) { f.onDestroyOptionsMenu(); } } } mCreatedMenus = newMenus; if (DEBUG) Log.d(TAG, "[onCreatePanelMenu] fragments create result: " + show); result |= show; if (DEBUG) Log.d(TAG, "[onCreatePanelMenu] returning " + result); return result; } return false; } @Override public boolean onPreparePanel(int featureId, View view, Menu menu) { if (DEBUG) Log.d(TAG, "[onPreparePanel] featureId: " + featureId + ", view: " + view + " menu: " + menu); if (featureId == Window.FEATURE_OPTIONS_PANEL) { boolean result = onPrepareOptionsMenu(menu); if (DEBUG) Log.d(TAG, "[onPreparePanel] activity prepare result: " + result); boolean show = false; if (mFragments.mActive != null) { for (int i = 0; i < mFragments.mAdded.size(); i++) { Fragment f = mFragments.mAdded.get(i); if (f != null && !f.mHidden && f.mHasMenu && f.mMenuVisible && f instanceof OnPrepareOptionsMenuListener) { show = true; ((OnPrepareOptionsMenuListener)f).onPrepareOptionsMenu(menu); } } } if (DEBUG) Log.d(TAG, "[onPreparePanel] fragments prepare result: " + show); result |= show; result &= menu.hasVisibleItems(); if (DEBUG) Log.d(TAG, "[onPreparePanel] returning " + result); return result; } return false; } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { if (DEBUG) Log.d(TAG, "[onMenuItemSelected] featureId: " + featureId + ", item: " + item); if (featureId == Window.FEATURE_OPTIONS_PANEL) { if (onOptionsItemSelected(item)) { return true; } if (mFragments.mActive != null) { for (int i = 0; i < mFragments.mAdded.size(); i++) { Fragment f = mFragments.mAdded.get(i); if (f != null && !f.mHidden && f.mHasMenu && f.mMenuVisible && f instanceof OnOptionsItemSelectedListener) { if (((OnOptionsItemSelectedListener)f).onOptionsItemSelected(item)) { return true; } } } } } return false; } public abstract boolean onCreateOptionsMenu(Menu menu); public abstract boolean onPrepareOptionsMenu(Menu menu); public abstract boolean onOptionsItemSelected(MenuItem item); public abstract MenuInflater getSupportMenuInflater(); }
1162584980-google-io
libprojects/abs/src/android/support/v4/app/_ActionBarSherlockTrojanHorse.java
Java
asf20
5,817
/* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.actionbarsherlock.view; import android.content.ComponentName; import android.content.Intent; import android.view.KeyEvent; /** * Interface for managing the items in a menu. * <p> * By default, every Activity supports an options menu of actions or options. * You can add items to this menu and handle clicks on your additions. The * easiest way of adding menu items is inflating an XML file into the * {@link Menu} via {@link MenuInflater}. The easiest way of attaching code to * clicks is via {@link Activity#onOptionsItemSelected(MenuItem)} and * {@link Activity#onContextItemSelected(MenuItem)}. * <p> * Different menu types support different features: * <ol> * <li><b>Context menus</b>: Do not support item shortcuts and item icons. * <li><b>Options menus</b>: The <b>icon menus</b> do not support item check * marks and only show the item's * {@link MenuItem#setTitleCondensed(CharSequence) condensed title}. The * <b>expanded menus</b> (only available if six or more menu items are visible, * reached via the 'More' item in the icon menu) do not show item icons, and * item check marks are discouraged. * <li><b>Sub menus</b>: Do not support item icons, or nested sub menus. * </ol> * * <div class="special reference"> * <h3>Developer Guides</h3> * <p>For more information about creating menus, read the * <a href="{@docRoot}guide/topics/ui/menus.html">Menus</a> developer guide.</p> * </div> */ public interface Menu { /** * This is the part of an order integer that the user can provide. * @hide */ static final int USER_MASK = 0x0000ffff; /** * Bit shift of the user portion of the order integer. * @hide */ static final int USER_SHIFT = 0; /** * This is the part of an order integer that supplies the category of the * item. * @hide */ static final int CATEGORY_MASK = 0xffff0000; /** * Bit shift of the category portion of the order integer. * @hide */ static final int CATEGORY_SHIFT = 16; /** * Value to use for group and item identifier integers when you don't care * about them. */ static final int NONE = 0; /** * First value for group and item identifier integers. */ static final int FIRST = 1; // Implementation note: Keep these CATEGORY_* in sync with the category enum // in attrs.xml /** * Category code for the order integer for items/groups that are part of a * container -- or/add this with your base value. */ static final int CATEGORY_CONTAINER = 0x00010000; /** * Category code for the order integer for items/groups that are provided by * the system -- or/add this with your base value. */ static final int CATEGORY_SYSTEM = 0x00020000; /** * Category code for the order integer for items/groups that are * user-supplied secondary (infrequently used) options -- or/add this with * your base value. */ static final int CATEGORY_SECONDARY = 0x00030000; /** * Category code for the order integer for items/groups that are * alternative actions on the data that is currently displayed -- or/add * this with your base value. */ static final int CATEGORY_ALTERNATIVE = 0x00040000; /** * Flag for {@link #addIntentOptions}: if set, do not automatically remove * any existing menu items in the same group. */ static final int FLAG_APPEND_TO_GROUP = 0x0001; /** * Flag for {@link #performShortcut}: if set, do not close the menu after * executing the shortcut. */ static final int FLAG_PERFORM_NO_CLOSE = 0x0001; /** * Flag for {@link #performShortcut(int, KeyEvent, int)}: if set, always * close the menu after executing the shortcut. Closing the menu also resets * the prepared state. */ static final int FLAG_ALWAYS_PERFORM_CLOSE = 0x0002; /** * Add a new item to the menu. This item displays the given title for its * label. * * @param title The text to display for the item. * @return The newly added menu item. */ public MenuItem add(CharSequence title); /** * Add a new item to the menu. This item displays the given title for its * label. * * @param titleRes Resource identifier of title string. * @return The newly added menu item. */ public MenuItem add(int titleRes); /** * Add a new item to the menu. This item displays the given title for its * label. * * @param groupId The group identifier that this item should be part of. * This can be used to define groups of items for batch state * changes. Normally use {@link #NONE} if an item should not be in a * group. * @param itemId Unique item ID. Use {@link #NONE} if you do not need a * unique ID. * @param order The order for the item. Use {@link #NONE} if you do not care * about the order. See {@link MenuItem#getOrder()}. * @param title The text to display for the item. * @return The newly added menu item. */ public MenuItem add(int groupId, int itemId, int order, CharSequence title); /** * Variation on {@link #add(int, int, int, CharSequence)} that takes a * string resource identifier instead of the string itself. * * @param groupId The group identifier that this item should be part of. * This can also be used to define groups of items for batch state * changes. Normally use {@link #NONE} if an item should not be in a * group. * @param itemId Unique item ID. Use {@link #NONE} if you do not need a * unique ID. * @param order The order for the item. Use {@link #NONE} if you do not care * about the order. See {@link MenuItem#getOrder()}. * @param titleRes Resource identifier of title string. * @return The newly added menu item. */ public MenuItem add(int groupId, int itemId, int order, int titleRes); /** * Add a new sub-menu to the menu. This item displays the given title for * its label. To modify other attributes on the submenu's menu item, use * {@link SubMenu#getItem()}. * * @param title The text to display for the item. * @return The newly added sub-menu */ SubMenu addSubMenu(final CharSequence title); /** * Add a new sub-menu to the menu. This item displays the given title for * its label. To modify other attributes on the submenu's menu item, use * {@link SubMenu#getItem()}. * * @param titleRes Resource identifier of title string. * @return The newly added sub-menu */ SubMenu addSubMenu(final int titleRes); /** * Add a new sub-menu to the menu. This item displays the given * <var>title</var> for its label. To modify other attributes on the * submenu's menu item, use {@link SubMenu#getItem()}. *<p> * Note that you can only have one level of sub-menus, i.e. you cannnot add * a subMenu to a subMenu: An {@link UnsupportedOperationException} will be * thrown if you try. * * @param groupId The group identifier that this item should be part of. * This can also be used to define groups of items for batch state * changes. Normally use {@link #NONE} if an item should not be in a * group. * @param itemId Unique item ID. Use {@link #NONE} if you do not need a * unique ID. * @param order The order for the item. Use {@link #NONE} if you do not care * about the order. See {@link MenuItem#getOrder()}. * @param title The text to display for the item. * @return The newly added sub-menu */ SubMenu addSubMenu(final int groupId, final int itemId, int order, final CharSequence title); /** * Variation on {@link #addSubMenu(int, int, int, CharSequence)} that takes * a string resource identifier for the title instead of the string itself. * * @param groupId The group identifier that this item should be part of. * This can also be used to define groups of items for batch state * changes. Normally use {@link #NONE} if an item should not be in a group. * @param itemId Unique item ID. Use {@link #NONE} if you do not need a unique ID. * @param order The order for the item. Use {@link #NONE} if you do not care about the * order. See {@link MenuItem#getOrder()}. * @param titleRes Resource identifier of title string. * @return The newly added sub-menu */ SubMenu addSubMenu(int groupId, int itemId, int order, int titleRes); /** * Add a group of menu items corresponding to actions that can be performed * for a particular Intent. The Intent is most often configured with a null * action, the data that the current activity is working with, and includes * either the {@link Intent#CATEGORY_ALTERNATIVE} or * {@link Intent#CATEGORY_SELECTED_ALTERNATIVE} to find activities that have * said they would like to be included as optional action. You can, however, * use any Intent you want. * * <p> * See {@link android.content.pm.PackageManager#queryIntentActivityOptions} * for more * details on the <var>caller</var>, <var>specifics</var>, and * <var>intent</var> arguments. The list returned by that function is used * to populate the resulting menu items. * * <p> * All of the menu items of possible options for the intent will be added * with the given group and id. You can use the group to control ordering of * the items in relation to other items in the menu. Normally this function * will automatically remove any existing items in the menu in the same * group and place a divider above and below the added items; this behavior * can be modified with the <var>flags</var> parameter. For each of the * generated items {@link MenuItem#setIntent} is called to associate the * appropriate Intent with the item; this means the activity will * automatically be started for you without having to do anything else. * * @param groupId The group identifier that the items should be part of. * This can also be used to define groups of items for batch state * changes. Normally use {@link #NONE} if the items should not be in * a group. * @param itemId Unique item ID. Use {@link #NONE} if you do not need a * unique ID. * @param order The order for the items. Use {@link #NONE} if you do not * care about the order. See {@link MenuItem#getOrder()}. * @param caller The current activity component name as defined by * queryIntentActivityOptions(). * @param specifics Specific items to place first as defined by * queryIntentActivityOptions(). * @param intent Intent describing the kinds of items to populate in the * list as defined by queryIntentActivityOptions(). * @param flags Additional options controlling how the items are added. * @param outSpecificItems Optional array in which to place the menu items * that were generated for each of the <var>specifics</var> that were * requested. Entries may be null if no activity was found for that * specific action. * @return The number of menu items that were added. * * @see #FLAG_APPEND_TO_GROUP * @see MenuItem#setIntent * @see android.content.pm.PackageManager#queryIntentActivityOptions */ public int addIntentOptions(int groupId, int itemId, int order, ComponentName caller, Intent[] specifics, Intent intent, int flags, MenuItem[] outSpecificItems); /** * Remove the item with the given identifier. * * @param id The item to be removed. If there is no item with this * identifier, nothing happens. */ public void removeItem(int id); /** * Remove all items in the given group. * * @param groupId The group to be removed. If there are no items in this * group, nothing happens. */ public void removeGroup(int groupId); /** * Remove all existing items from the menu, leaving it empty as if it had * just been created. */ public void clear(); /** * Control whether a particular group of items can show a check mark. This * is similar to calling {@link MenuItem#setCheckable} on all of the menu items * with the given group identifier, but in addition you can control whether * this group contains a mutually-exclusive set items. This should be called * after the items of the group have been added to the menu. * * @param group The group of items to operate on. * @param checkable Set to true to allow a check mark, false to * disallow. The default is false. * @param exclusive If set to true, only one item in this group can be * checked at a time; checking an item will automatically * uncheck all others in the group. If set to false, each * item can be checked independently of the others. * * @see MenuItem#setCheckable * @see MenuItem#setChecked */ public void setGroupCheckable(int group, boolean checkable, boolean exclusive); /** * Show or hide all menu items that are in the given group. * * @param group The group of items to operate on. * @param visible If true the items are visible, else they are hidden. * * @see MenuItem#setVisible */ public void setGroupVisible(int group, boolean visible); /** * Enable or disable all menu items that are in the given group. * * @param group The group of items to operate on. * @param enabled If true the items will be enabled, else they will be disabled. * * @see MenuItem#setEnabled */ public void setGroupEnabled(int group, boolean enabled); /** * Return whether the menu currently has item items that are visible. * * @return True if there is one or more item visible, * else false. */ public boolean hasVisibleItems(); /** * Return the menu item with a particular identifier. * * @param id The identifier to find. * * @return The menu item object, or null if there is no item with * this identifier. */ public MenuItem findItem(int id); /** * Get the number of items in the menu. Note that this will change any * times items are added or removed from the menu. * * @return The item count. */ public int size(); /** * Gets the menu item at the given index. * * @param index The index of the menu item to return. * @return The menu item. * @exception IndexOutOfBoundsException * when {@code index < 0 || >= size()} */ public MenuItem getItem(int index); /** * Closes the menu, if open. */ public void close(); /** * Execute the menu item action associated with the given shortcut * character. * * @param keyCode The keycode of the shortcut key. * @param event Key event message. * @param flags Additional option flags or 0. * * @return If the given shortcut exists and is shown, returns * true; else returns false. * * @see #FLAG_PERFORM_NO_CLOSE */ public boolean performShortcut(int keyCode, KeyEvent event, int flags); /** * Is a keypress one of the defined shortcut keys for this window. * @param keyCode the key code from {@link KeyEvent} to check. * @param event the {@link KeyEvent} to use to help check. */ boolean isShortcutKey(int keyCode, KeyEvent event); /** * Execute the menu item action associated with the given menu identifier. * * @param id Identifier associated with the menu item. * @param flags Additional option flags or 0. * * @return If the given identifier exists and is shown, returns * true; else returns false. * * @see #FLAG_PERFORM_NO_CLOSE */ public boolean performIdentifierAction(int id, int flags); /** * Control whether the menu should be running in qwerty mode (alphabetic * shortcuts) or 12-key mode (numeric shortcuts). * * @param isQwerty If true the menu will use alphabetic shortcuts; else it * will use numeric shortcuts. */ public void setQwertyMode(boolean isQwerty); }
1162584980-google-io
libprojects/abs/src/com/actionbarsherlock/view/Menu.java
Java
asf20
17,460
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.actionbarsherlock.view; import android.content.Intent; import android.graphics.drawable.Drawable; import android.view.ContextMenu.ContextMenuInfo; import android.view.View; /** * Interface for direct access to a previously created menu item. * <p> * An Item is returned by calling one of the {@link android.view.Menu#add} * methods. * <p> * For a feature set of specific menu types, see {@link Menu}. * * <div class="special reference"> * <h3>Developer Guides</h3> * <p>For information about creating menus, read the * <a href="{@docRoot}guide/topics/ui/menus.html">Menus</a> developer guide.</p> * </div> */ public interface MenuItem { /* * These should be kept in sync with attrs.xml enum constants for showAsAction */ /** Never show this item as a button in an Action Bar. */ public static final int SHOW_AS_ACTION_NEVER = android.view.MenuItem.SHOW_AS_ACTION_NEVER; /** Show this item as a button in an Action Bar if the system decides there is room for it. */ public static final int SHOW_AS_ACTION_IF_ROOM = android.view.MenuItem.SHOW_AS_ACTION_IF_ROOM; /** * Always show this item as a button in an Action Bar. * Use sparingly! If too many items are set to always show in the Action Bar it can * crowd the Action Bar and degrade the user experience on devices with smaller screens. * A good rule of thumb is to have no more than 2 items set to always show at a time. */ public static final int SHOW_AS_ACTION_ALWAYS = android.view.MenuItem.SHOW_AS_ACTION_ALWAYS; /** * When this item is in the action bar, always show it with a text label even if * it also has an icon specified. */ public static final int SHOW_AS_ACTION_WITH_TEXT = android.view.MenuItem.SHOW_AS_ACTION_WITH_TEXT; /** * This item's action view collapses to a normal menu item. * When expanded, the action view temporarily takes over * a larger segment of its container. */ public static final int SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW = android.view.MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW; /** * Interface definition for a callback to be invoked when a menu item is * clicked. * * @see Activity#onContextItemSelected(MenuItem) * @see Activity#onOptionsItemSelected(MenuItem) */ public interface OnMenuItemClickListener { /** * Called when a menu item has been invoked. This is the first code * that is executed; if it returns true, no other callbacks will be * executed. * * @param item The menu item that was invoked. * * @return Return true to consume this click and prevent others from * executing. */ public boolean onMenuItemClick(MenuItem item); } /** * Interface definition for a callback to be invoked when a menu item * marked with {@link MenuItem#SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW} is * expanded or collapsed. * * @see MenuItem#expandActionView() * @see MenuItem#collapseActionView() * @see MenuItem#setShowAsActionFlags(int) */ public interface OnActionExpandListener { /** * Called when a menu item with {@link MenuItem#SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW} * is expanded. * @param item Item that was expanded * @return true if the item should expand, false if expansion should be suppressed. */ public boolean onMenuItemActionExpand(MenuItem item); /** * Called when a menu item with {@link MenuItem#SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW} * is collapsed. * @param item Item that was collapsed * @return true if the item should collapse, false if collapsing should be suppressed. */ public boolean onMenuItemActionCollapse(MenuItem item); } /** * Return the identifier for this menu item. The identifier can not * be changed after the menu is created. * * @return The menu item's identifier. */ public int getItemId(); /** * Return the group identifier that this menu item is part of. The group * identifier can not be changed after the menu is created. * * @return The menu item's group identifier. */ public int getGroupId(); /** * Return the category and order within the category of this item. This * item will be shown before all items (within its category) that have * order greater than this value. * <p> * An order integer contains the item's category (the upper bits of the * integer; set by or/add the category with the order within the * category) and the ordering of the item within that category (the * lower bits). Example categories are {@link Menu#CATEGORY_SYSTEM}, * {@link Menu#CATEGORY_SECONDARY}, {@link Menu#CATEGORY_ALTERNATIVE}, * {@link Menu#CATEGORY_CONTAINER}. See {@link Menu} for a full list. * * @return The order of this item. */ public int getOrder(); /** * Change the title associated with this item. * * @param title The new text to be displayed. * @return This Item so additional setters can be called. */ public MenuItem setTitle(CharSequence title); /** * Change the title associated with this item. * <p> * Some menu types do not sufficient space to show the full title, and * instead a condensed title is preferred. See {@link Menu} for more * information. * * @param title The resource id of the new text to be displayed. * @return This Item so additional setters can be called. * @see #setTitleCondensed(CharSequence) */ public MenuItem setTitle(int title); /** * Retrieve the current title of the item. * * @return The title. */ public CharSequence getTitle(); /** * Change the condensed title associated with this item. The condensed * title is used in situations where the normal title may be too long to * be displayed. * * @param title The new text to be displayed as the condensed title. * @return This Item so additional setters can be called. */ public MenuItem setTitleCondensed(CharSequence title); /** * Retrieve the current condensed title of the item. If a condensed * title was never set, it will return the normal title. * * @return The condensed title, if it exists. * Otherwise the normal title. */ public CharSequence getTitleCondensed(); /** * Change the icon associated with this item. This icon will not always be * shown, so the title should be sufficient in describing this item. See * {@link Menu} for the menu types that support icons. * * @param icon The new icon (as a Drawable) to be displayed. * @return This Item so additional setters can be called. */ public MenuItem setIcon(Drawable icon); /** * Change the icon associated with this item. This icon will not always be * shown, so the title should be sufficient in describing this item. See * {@link Menu} for the menu types that support icons. * <p> * This method will set the resource ID of the icon which will be used to * lazily get the Drawable when this item is being shown. * * @param iconRes The new icon (as a resource ID) to be displayed. * @return This Item so additional setters can be called. */ public MenuItem setIcon(int iconRes); /** * Returns the icon for this item as a Drawable (getting it from resources if it hasn't been * loaded before). * * @return The icon as a Drawable. */ public Drawable getIcon(); /** * Change the Intent associated with this item. By default there is no * Intent associated with a menu item. If you set one, and nothing * else handles the item, then the default behavior will be to call * {@link android.content.Context#startActivity} with the given Intent. * * <p>Note that setIntent() can not be used with the versions of * {@link Menu#add} that take a Runnable, because {@link Runnable#run} * does not return a value so there is no way to tell if it handled the * item. In this case it is assumed that the Runnable always handles * the item, and the intent will never be started. * * @see #getIntent * @param intent The Intent to associated with the item. This Intent * object is <em>not</em> copied, so be careful not to * modify it later. * @return This Item so additional setters can be called. */ public MenuItem setIntent(Intent intent); /** * Return the Intent associated with this item. This returns a * reference to the Intent which you can change as desired to modify * what the Item is holding. * * @see #setIntent * @return Returns the last value supplied to {@link #setIntent}, or * null. */ public Intent getIntent(); /** * Change both the numeric and alphabetic shortcut associated with this * item. Note that the shortcut will be triggered when the key that * generates the given character is pressed alone or along with with the alt * key. Also note that case is not significant and that alphabetic shortcut * characters will be displayed in lower case. * <p> * See {@link Menu} for the menu types that support shortcuts. * * @param numericChar The numeric shortcut key. This is the shortcut when * using a numeric (e.g., 12-key) keyboard. * @param alphaChar The alphabetic shortcut key. This is the shortcut when * using a keyboard with alphabetic keys. * @return This Item so additional setters can be called. */ public MenuItem setShortcut(char numericChar, char alphaChar); /** * Change the numeric shortcut associated with this item. * <p> * See {@link Menu} for the menu types that support shortcuts. * * @param numericChar The numeric shortcut key. This is the shortcut when * using a 12-key (numeric) keyboard. * @return This Item so additional setters can be called. */ public MenuItem setNumericShortcut(char numericChar); /** * Return the char for this menu item's numeric (12-key) shortcut. * * @return Numeric character to use as a shortcut. */ public char getNumericShortcut(); /** * Change the alphabetic shortcut associated with this item. The shortcut * will be triggered when the key that generates the given character is * pressed alone or along with with the alt key. Case is not significant and * shortcut characters will be displayed in lower case. Note that menu items * with the characters '\b' or '\n' as shortcuts will get triggered by the * Delete key or Carriage Return key, respectively. * <p> * See {@link Menu} for the menu types that support shortcuts. * * @param alphaChar The alphabetic shortcut key. This is the shortcut when * using a keyboard with alphabetic keys. * @return This Item so additional setters can be called. */ public MenuItem setAlphabeticShortcut(char alphaChar); /** * Return the char for this menu item's alphabetic shortcut. * * @return Alphabetic character to use as a shortcut. */ public char getAlphabeticShortcut(); /** * Control whether this item can display a check mark. Setting this does * not actually display a check mark (see {@link #setChecked} for that); * rather, it ensures there is room in the item in which to display a * check mark. * <p> * See {@link Menu} for the menu types that support check marks. * * @param checkable Set to true to allow a check mark, false to * disallow. The default is false. * @see #setChecked * @see #isCheckable * @see Menu#setGroupCheckable * @return This Item so additional setters can be called. */ public MenuItem setCheckable(boolean checkable); /** * Return whether the item can currently display a check mark. * * @return If a check mark can be displayed, returns true. * * @see #setCheckable */ public boolean isCheckable(); /** * Control whether this item is shown with a check mark. Note that you * must first have enabled checking with {@link #setCheckable} or else * the check mark will not appear. If this item is a member of a group that contains * mutually-exclusive items (set via {@link Menu#setGroupCheckable(int, boolean, boolean)}, * the other items in the group will be unchecked. * <p> * See {@link Menu} for the menu types that support check marks. * * @see #setCheckable * @see #isChecked * @see Menu#setGroupCheckable * @param checked Set to true to display a check mark, false to hide * it. The default value is false. * @return This Item so additional setters can be called. */ public MenuItem setChecked(boolean checked); /** * Return whether the item is currently displaying a check mark. * * @return If a check mark is displayed, returns true. * * @see #setChecked */ public boolean isChecked(); /** * Sets the visibility of the menu item. Even if a menu item is not visible, * it may still be invoked via its shortcut (to completely disable an item, * set it to invisible and {@link #setEnabled(boolean) disabled}). * * @param visible If true then the item will be visible; if false it is * hidden. * @return This Item so additional setters can be called. */ public MenuItem setVisible(boolean visible); /** * Return the visibility of the menu item. * * @return If true the item is visible; else it is hidden. */ public boolean isVisible(); /** * Sets whether the menu item is enabled. Disabling a menu item will not * allow it to be invoked via its shortcut. The menu item will still be * visible. * * @param enabled If true then the item will be invokable; if false it is * won't be invokable. * @return This Item so additional setters can be called. */ public MenuItem setEnabled(boolean enabled); /** * Return the enabled state of the menu item. * * @return If true the item is enabled and hence invokable; else it is not. */ public boolean isEnabled(); /** * Check whether this item has an associated sub-menu. I.e. it is a * sub-menu of another menu. * * @return If true this item has a menu; else it is a * normal item. */ public boolean hasSubMenu(); /** * Get the sub-menu to be invoked when this item is selected, if it has * one. See {@link #hasSubMenu()}. * * @return The associated menu if there is one, else null */ public SubMenu getSubMenu(); /** * Set a custom listener for invocation of this menu item. In most * situations, it is more efficient and easier to use * {@link Activity#onOptionsItemSelected(MenuItem)} or * {@link Activity#onContextItemSelected(MenuItem)}. * * @param menuItemClickListener The object to receive invokations. * @return This Item so additional setters can be called. * @see Activity#onOptionsItemSelected(MenuItem) * @see Activity#onContextItemSelected(MenuItem) */ public MenuItem setOnMenuItemClickListener(MenuItem.OnMenuItemClickListener menuItemClickListener); /** * Gets the extra information linked to this menu item. This extra * information is set by the View that added this menu item to the * menu. * * @see OnCreateContextMenuListener * @return The extra information linked to the View that added this * menu item to the menu. This can be null. */ public ContextMenuInfo getMenuInfo(); /** * Sets how this item should display in the presence of an Action Bar. * The parameter actionEnum is a flag set. One of {@link #SHOW_AS_ACTION_ALWAYS}, * {@link #SHOW_AS_ACTION_IF_ROOM}, or {@link #SHOW_AS_ACTION_NEVER} should * be used, and you may optionally OR the value with {@link #SHOW_AS_ACTION_WITH_TEXT}. * SHOW_AS_ACTION_WITH_TEXT requests that when the item is shown as an action, * it should be shown with a text label. * * @param actionEnum How the item should display. One of * {@link #SHOW_AS_ACTION_ALWAYS}, {@link #SHOW_AS_ACTION_IF_ROOM}, or * {@link #SHOW_AS_ACTION_NEVER}. SHOW_AS_ACTION_NEVER is the default. * * @see android.app.ActionBar * @see #setActionView(View) */ public void setShowAsAction(int actionEnum); /** * Sets how this item should display in the presence of an Action Bar. * The parameter actionEnum is a flag set. One of {@link #SHOW_AS_ACTION_ALWAYS}, * {@link #SHOW_AS_ACTION_IF_ROOM}, or {@link #SHOW_AS_ACTION_NEVER} should * be used, and you may optionally OR the value with {@link #SHOW_AS_ACTION_WITH_TEXT}. * SHOW_AS_ACTION_WITH_TEXT requests that when the item is shown as an action, * it should be shown with a text label. * * <p>Note: This method differs from {@link #setShowAsAction(int)} only in that it * returns the current MenuItem instance for call chaining. * * @param actionEnum How the item should display. One of * {@link #SHOW_AS_ACTION_ALWAYS}, {@link #SHOW_AS_ACTION_IF_ROOM}, or * {@link #SHOW_AS_ACTION_NEVER}. SHOW_AS_ACTION_NEVER is the default. * * @see android.app.ActionBar * @see #setActionView(View) * @return This MenuItem instance for call chaining. */ public MenuItem setShowAsActionFlags(int actionEnum); /** * Set an action view for this menu item. An action view will be displayed in place * of an automatically generated menu item element in the UI when this item is shown * as an action within a parent. * <p> * <strong>Note:</strong> Setting an action view overrides the action provider * set via {@link #setActionProvider(ActionProvider)}. * </p> * * @param view View to use for presenting this item to the user. * @return This Item so additional setters can be called. * * @see #setShowAsAction(int) */ public MenuItem setActionView(View view); /** * Set an action view for this menu item. An action view will be displayed in place * of an automatically generated menu item element in the UI when this item is shown * as an action within a parent. * <p> * <strong>Note:</strong> Setting an action view overrides the action provider * set via {@link #setActionProvider(ActionProvider)}. * </p> * * @param resId Layout resource to use for presenting this item to the user. * @return This Item so additional setters can be called. * * @see #setShowAsAction(int) */ public MenuItem setActionView(int resId); /** * Returns the currently set action view for this menu item. * * @return This item's action view * * @see #setActionView(View) * @see #setShowAsAction(int) */ public View getActionView(); /** * Sets the {@link ActionProvider} responsible for creating an action view if * the item is placed on the action bar. The provider also provides a default * action invoked if the item is placed in the overflow menu. * <p> * <strong>Note:</strong> Setting an action provider overrides the action view * set via {@link #setActionView(int)} or {@link #setActionView(View)}. * </p> * * @param actionProvider The action provider. * @return This Item so additional setters can be called. * * @see ActionProvider */ public MenuItem setActionProvider(ActionProvider actionProvider); /** * Gets the {@link ActionProvider}. * * @return The action provider. * * @see ActionProvider * @see #setActionProvider(ActionProvider) */ public ActionProvider getActionProvider(); /** * Expand the action view associated with this menu item. * The menu item must have an action view set, as well as * the showAsAction flag {@link #SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW}. * If a listener has been set using {@link #setOnActionExpandListener(OnActionExpandListener)} * it will have its {@link OnActionExpandListener#onMenuItemActionExpand(MenuItem)} * method invoked. The listener may return false from this method to prevent expanding * the action view. * * @return true if the action view was expanded, false otherwise. */ public boolean expandActionView(); /** * Collapse the action view associated with this menu item. * The menu item must have an action view set, as well as the showAsAction flag * {@link #SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW}. If a listener has been set using * {@link #setOnActionExpandListener(OnActionExpandListener)} it will have its * {@link OnActionExpandListener#onMenuItemActionCollapse(MenuItem)} method invoked. * The listener may return false from this method to prevent collapsing the action view. * * @return true if the action view was collapsed, false otherwise. */ public boolean collapseActionView(); /** * Returns true if this menu item's action view has been expanded. * * @return true if the item's action view is expanded, false otherwise. * * @see #expandActionView() * @see #collapseActionView() * @see #SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW * @see OnActionExpandListener */ public boolean isActionViewExpanded(); /** * Set an {@link OnActionExpandListener} on this menu item to be notified when * the associated action view is expanded or collapsed. The menu item must * be configured to expand or collapse its action view using the flag * {@link #SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW}. * * @param listener Listener that will respond to expand/collapse events * @return This menu item instance for call chaining */ public MenuItem setOnActionExpandListener(OnActionExpandListener listener); }
1162584980-google-io
libprojects/abs/src/com/actionbarsherlock/view/MenuItem.java
Java
asf20
23,294
/* * Copyright (C) 2006 The Android Open Source Project * 2011 Jake Wharton * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.actionbarsherlock.view; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.Context; import android.content.res.TypedArray; import android.content.res.XmlResourceParser; import android.util.AttributeSet; import android.util.Log; import android.util.TypedValue; import android.util.Xml; import android.view.InflateException; import android.view.View; import com.actionbarsherlock.R; import com.actionbarsherlock.internal.view.menu.MenuItemImpl; /** * This class is used to instantiate menu XML files into Menu objects. * <p> * For performance reasons, menu inflation relies heavily on pre-processing of * XML files that is done at build time. Therefore, it is not currently possible * to use MenuInflater with an XmlPullParser over a plain XML file at runtime; * it only works with an XmlPullParser returned from a compiled resource (R. * <em>something</em> file.) */ public class MenuInflater { private static final String LOG_TAG = "MenuInflater"; /** Menu tag name in XML. */ private static final String XML_MENU = "menu"; /** Group tag name in XML. */ private static final String XML_GROUP = "group"; /** Item tag name in XML. */ private static final String XML_ITEM = "item"; private static final int NO_ID = 0; private static final Class<?>[] ACTION_VIEW_CONSTRUCTOR_SIGNATURE = new Class[] {Context.class}; private static final Class<?>[] ACTION_PROVIDER_CONSTRUCTOR_SIGNATURE = ACTION_VIEW_CONSTRUCTOR_SIGNATURE; private final Object[] mActionViewConstructorArguments; private final Object[] mActionProviderConstructorArguments; private Context mContext; /** * Constructs a menu inflater. * * @see Activity#getMenuInflater() */ public MenuInflater(Context context) { mContext = context; mActionViewConstructorArguments = new Object[] {context}; mActionProviderConstructorArguments = mActionViewConstructorArguments; } /** * Inflate a menu hierarchy from the specified XML resource. Throws * {@link InflateException} if there is an error. * * @param menuRes Resource ID for an XML layout resource to load (e.g., * <code>R.menu.main_activity</code>) * @param menu The Menu to inflate into. The items and submenus will be * added to this Menu. */ public void inflate(int menuRes, Menu menu) { XmlResourceParser parser = null; try { parser = mContext.getResources().getLayout(menuRes); AttributeSet attrs = Xml.asAttributeSet(parser); parseMenu(parser, attrs, menu); } catch (XmlPullParserException e) { throw new InflateException("Error inflating menu XML", e); } catch (IOException e) { throw new InflateException("Error inflating menu XML", e); } finally { if (parser != null) parser.close(); } } /** * Called internally to fill the given menu. If a sub menu is seen, it will * call this recursively. */ private void parseMenu(XmlPullParser parser, AttributeSet attrs, Menu menu) throws XmlPullParserException, IOException { MenuState menuState = new MenuState(menu); int eventType = parser.getEventType(); String tagName; boolean lookingForEndOfUnknownTag = false; String unknownTagName = null; // This loop will skip to the menu start tag do { if (eventType == XmlPullParser.START_TAG) { tagName = parser.getName(); if (tagName.equals(XML_MENU)) { // Go to next tag eventType = parser.next(); break; } throw new RuntimeException("Expecting menu, got " + tagName); } eventType = parser.next(); } while (eventType != XmlPullParser.END_DOCUMENT); boolean reachedEndOfMenu = false; while (!reachedEndOfMenu) { switch (eventType) { case XmlPullParser.START_TAG: if (lookingForEndOfUnknownTag) { break; } tagName = parser.getName(); if (tagName.equals(XML_GROUP)) { menuState.readGroup(attrs); } else if (tagName.equals(XML_ITEM)) { menuState.readItem(attrs); } else if (tagName.equals(XML_MENU)) { // A menu start tag denotes a submenu for an item SubMenu subMenu = menuState.addSubMenuItem(); // Parse the submenu into returned SubMenu parseMenu(parser, attrs, subMenu); } else { lookingForEndOfUnknownTag = true; unknownTagName = tagName; } break; case XmlPullParser.END_TAG: tagName = parser.getName(); if (lookingForEndOfUnknownTag && tagName.equals(unknownTagName)) { lookingForEndOfUnknownTag = false; unknownTagName = null; } else if (tagName.equals(XML_GROUP)) { menuState.resetGroup(); } else if (tagName.equals(XML_ITEM)) { // Add the item if it hasn't been added (if the item was // a submenu, it would have been added already) if (!menuState.hasAddedItem()) { if (menuState.itemActionProvider != null && menuState.itemActionProvider.hasSubMenu()) { menuState.addSubMenuItem(); } else { menuState.addItem(); } } } else if (tagName.equals(XML_MENU)) { reachedEndOfMenu = true; } break; case XmlPullParser.END_DOCUMENT: throw new RuntimeException("Unexpected end of document"); } eventType = parser.next(); } } private static class InflatedOnMenuItemClickListener implements MenuItem.OnMenuItemClickListener { private static final Class<?>[] PARAM_TYPES = new Class[] { MenuItem.class }; private Context mContext; private Method mMethod; public InflatedOnMenuItemClickListener(Context context, String methodName) { mContext = context; Class<?> c = context.getClass(); try { mMethod = c.getMethod(methodName, PARAM_TYPES); } catch (Exception e) { InflateException ex = new InflateException( "Couldn't resolve menu item onClick handler " + methodName + " in class " + c.getName()); ex.initCause(e); throw ex; } } public boolean onMenuItemClick(MenuItem item) { try { if (mMethod.getReturnType() == Boolean.TYPE) { return (Boolean) mMethod.invoke(mContext, item); } else { mMethod.invoke(mContext, item); return true; } } catch (Exception e) { throw new RuntimeException(e); } } } /** * State for the current menu. * <p> * Groups can not be nested unless there is another menu (which will have * its state class). */ private class MenuState { private Menu menu; /* * Group state is set on items as they are added, allowing an item to * override its group state. (As opposed to set on items at the group end tag.) */ private int groupId; private int groupCategory; private int groupOrder; private int groupCheckable; private boolean groupVisible; private boolean groupEnabled; private boolean itemAdded; private int itemId; private int itemCategoryOrder; private CharSequence itemTitle; private CharSequence itemTitleCondensed; private int itemIconResId; private char itemAlphabeticShortcut; private char itemNumericShortcut; /** * Sync to attrs.xml enum: * - 0: none * - 1: all * - 2: exclusive */ private int itemCheckable; private boolean itemChecked; private boolean itemVisible; private boolean itemEnabled; /** * Sync to attrs.xml enum, values in MenuItem: * - 0: never * - 1: ifRoom * - 2: always * - -1: Safe sentinel for "no value". */ private int itemShowAsAction; private int itemActionViewLayout; private String itemActionViewClassName; private String itemActionProviderClassName; private String itemListenerMethodName; private ActionProvider itemActionProvider; private static final int defaultGroupId = NO_ID; private static final int defaultItemId = NO_ID; private static final int defaultItemCategory = 0; private static final int defaultItemOrder = 0; private static final int defaultItemCheckable = 0; private static final boolean defaultItemChecked = false; private static final boolean defaultItemVisible = true; private static final boolean defaultItemEnabled = true; public MenuState(final Menu menu) { this.menu = menu; resetGroup(); } public void resetGroup() { groupId = defaultGroupId; groupCategory = defaultItemCategory; groupOrder = defaultItemOrder; groupCheckable = defaultItemCheckable; groupVisible = defaultItemVisible; groupEnabled = defaultItemEnabled; } /** * Called when the parser is pointing to a group tag. */ public void readGroup(AttributeSet attrs) { TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.SherlockMenuGroup); groupId = a.getResourceId(R.styleable.SherlockMenuGroup_android_id, defaultGroupId); groupCategory = a.getInt(R.styleable.SherlockMenuGroup_android_menuCategory, defaultItemCategory); groupOrder = a.getInt(R.styleable.SherlockMenuGroup_android_orderInCategory, defaultItemOrder); groupCheckable = a.getInt(R.styleable.SherlockMenuGroup_android_checkableBehavior, defaultItemCheckable); groupVisible = a.getBoolean(R.styleable.SherlockMenuGroup_android_visible, defaultItemVisible); groupEnabled = a.getBoolean(R.styleable.SherlockMenuGroup_android_enabled, defaultItemEnabled); a.recycle(); } /** * Called when the parser is pointing to an item tag. */ public void readItem(AttributeSet attrs) { TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.SherlockMenuItem); // Inherit attributes from the group as default value itemId = a.getResourceId(R.styleable.SherlockMenuItem_android_id, defaultItemId); final int category = a.getInt(R.styleable.SherlockMenuItem_android_menuCategory, groupCategory); final int order = a.getInt(R.styleable.SherlockMenuItem_android_orderInCategory, groupOrder); itemCategoryOrder = (category & Menu.CATEGORY_MASK) | (order & Menu.USER_MASK); itemTitle = a.getText(R.styleable.SherlockMenuItem_android_title); itemTitleCondensed = a.getText(R.styleable.SherlockMenuItem_android_titleCondensed); itemIconResId = a.getResourceId(R.styleable.SherlockMenuItem_android_icon, 0); itemAlphabeticShortcut = getShortcut(a.getString(R.styleable.SherlockMenuItem_android_alphabeticShortcut)); itemNumericShortcut = getShortcut(a.getString(R.styleable.SherlockMenuItem_android_numericShortcut)); if (a.hasValue(R.styleable.SherlockMenuItem_android_checkable)) { // Item has attribute checkable, use it itemCheckable = a.getBoolean(R.styleable.SherlockMenuItem_android_checkable, false) ? 1 : 0; } else { // Item does not have attribute, use the group's (group can have one more state // for checkable that represents the exclusive checkable) itemCheckable = groupCheckable; } itemChecked = a.getBoolean(R.styleable.SherlockMenuItem_android_checked, defaultItemChecked); itemVisible = a.getBoolean(R.styleable.SherlockMenuItem_android_visible, groupVisible); itemEnabled = a.getBoolean(R.styleable.SherlockMenuItem_android_enabled, groupEnabled); TypedValue value = new TypedValue(); a.getValue(R.styleable.SherlockMenuItem_android_showAsAction, value); itemShowAsAction = value.type == TypedValue.TYPE_INT_HEX ? value.data : -1; itemListenerMethodName = a.getString(R.styleable.SherlockMenuItem_android_onClick); itemActionViewLayout = a.getResourceId(R.styleable.SherlockMenuItem_android_actionLayout, 0); itemActionViewClassName = a.getString(R.styleable.SherlockMenuItem_android_actionViewClass); itemActionProviderClassName = a.getString(R.styleable.SherlockMenuItem_android_actionProviderClass); final boolean hasActionProvider = itemActionProviderClassName != null; if (hasActionProvider && itemActionViewLayout == 0 && itemActionViewClassName == null) { itemActionProvider = newInstance(itemActionProviderClassName, ACTION_PROVIDER_CONSTRUCTOR_SIGNATURE, mActionProviderConstructorArguments); } else { if (hasActionProvider) { Log.w(LOG_TAG, "Ignoring attribute 'actionProviderClass'." + " Action view already specified."); } itemActionProvider = null; } a.recycle(); itemAdded = false; } private char getShortcut(String shortcutString) { if (shortcutString == null) { return 0; } else { return shortcutString.charAt(0); } } private void setItem(MenuItem item) { item.setChecked(itemChecked) .setVisible(itemVisible) .setEnabled(itemEnabled) .setCheckable(itemCheckable >= 1) .setTitleCondensed(itemTitleCondensed) .setIcon(itemIconResId) .setAlphabeticShortcut(itemAlphabeticShortcut) .setNumericShortcut(itemNumericShortcut); if (itemShowAsAction >= 0) { item.setShowAsAction(itemShowAsAction); } if (itemListenerMethodName != null) { if (mContext.isRestricted()) { throw new IllegalStateException("The android:onClick attribute cannot " + "be used within a restricted context"); } item.setOnMenuItemClickListener( new InflatedOnMenuItemClickListener(mContext, itemListenerMethodName)); } if (itemCheckable >= 2) { if (item instanceof MenuItemImpl) { MenuItemImpl impl = (MenuItemImpl) item; impl.setExclusiveCheckable(true); } else { menu.setGroupCheckable(groupId, true, true); } } boolean actionViewSpecified = false; if (itemActionViewClassName != null) { View actionView = (View) newInstance(itemActionViewClassName, ACTION_VIEW_CONSTRUCTOR_SIGNATURE, mActionViewConstructorArguments); item.setActionView(actionView); actionViewSpecified = true; } if (itemActionViewLayout > 0) { if (!actionViewSpecified) { item.setActionView(itemActionViewLayout); actionViewSpecified = true; } else { Log.w(LOG_TAG, "Ignoring attribute 'itemActionViewLayout'." + " Action view already specified."); } } if (itemActionProvider != null) { item.setActionProvider(itemActionProvider); } } public void addItem() { itemAdded = true; setItem(menu.add(groupId, itemId, itemCategoryOrder, itemTitle)); } public SubMenu addSubMenuItem() { itemAdded = true; SubMenu subMenu = menu.addSubMenu(groupId, itemId, itemCategoryOrder, itemTitle); setItem(subMenu.getItem()); return subMenu; } public boolean hasAddedItem() { return itemAdded; } @SuppressWarnings("unchecked") private <T> T newInstance(String className, Class<?>[] constructorSignature, Object[] arguments) { try { Class<?> clazz = mContext.getClassLoader().loadClass(className); Constructor<?> constructor = clazz.getConstructor(constructorSignature); return (T) constructor.newInstance(arguments); } catch (Exception e) { Log.w(LOG_TAG, "Cannot instantiate class: " + className, e); } return null; } } }
1162584980-google-io
libprojects/abs/src/com/actionbarsherlock/view/MenuInflater.java
Java
asf20
19,430
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.actionbarsherlock.view; /** * When a {@link View} implements this interface it will receive callbacks * when expanded or collapsed as an action view alongside the optional, * app-specified callbacks to {@link OnActionExpandListener}. * * <p>See {@link MenuItem} for more information about action views. * See {@link android.app.ActionBar} for more information about the action bar. */ public interface CollapsibleActionView { /** * Called when this view is expanded as an action view. * See {@link MenuItem#expandActionView()}. */ public void onActionViewExpanded(); /** * Called when this view is collapsed as an action view. * See {@link MenuItem#collapseActionView()}. */ public void onActionViewCollapsed(); }
1162584980-google-io
libprojects/abs/src/com/actionbarsherlock/view/CollapsibleActionView.java
Java
asf20
1,402
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.actionbarsherlock.view; import android.graphics.drawable.Drawable; import android.view.View; /** * Subclass of {@link Menu} for sub menus. * <p> * Sub menus do not support item icons, or nested sub menus. * * <div class="special reference"> * <h3>Developer Guides</h3> * <p>For information about creating menus, read the * <a href="{@docRoot}guide/topics/ui/menus.html">Menus</a> developer guide.</p> * </div> */ public interface SubMenu extends Menu { /** * Sets the submenu header's title to the title given in <var>titleRes</var> * resource identifier. * * @param titleRes The string resource identifier used for the title. * @return This SubMenu so additional setters can be called. */ public SubMenu setHeaderTitle(int titleRes); /** * Sets the submenu header's title to the title given in <var>title</var>. * * @param title The character sequence used for the title. * @return This SubMenu so additional setters can be called. */ public SubMenu setHeaderTitle(CharSequence title); /** * Sets the submenu header's icon to the icon given in <var>iconRes</var> * resource id. * * @param iconRes The resource identifier used for the icon. * @return This SubMenu so additional setters can be called. */ public SubMenu setHeaderIcon(int iconRes); /** * Sets the submenu header's icon to the icon given in <var>icon</var> * {@link Drawable}. * * @param icon The {@link Drawable} used for the icon. * @return This SubMenu so additional setters can be called. */ public SubMenu setHeaderIcon(Drawable icon); /** * Sets the header of the submenu to the {@link View} given in * <var>view</var>. This replaces the header title and icon (and those * replace this). * * @param view The {@link View} used for the header. * @return This SubMenu so additional setters can be called. */ public SubMenu setHeaderView(View view); /** * Clears the header of the submenu. */ public void clearHeader(); /** * Change the icon associated with this submenu's item in its parent menu. * * @see MenuItem#setIcon(int) * @param iconRes The new icon (as a resource ID) to be displayed. * @return This SubMenu so additional setters can be called. */ public SubMenu setIcon(int iconRes); /** * Change the icon associated with this submenu's item in its parent menu. * * @see MenuItem#setIcon(Drawable) * @param icon The new icon (as a Drawable) to be displayed. * @return This SubMenu so additional setters can be called. */ public SubMenu setIcon(Drawable icon); /** * Gets the {@link MenuItem} that represents this submenu in the parent * menu. Use this for setting additional item attributes. * * @return The {@link MenuItem} that launches the submenu when invoked. */ public MenuItem getItem(); }
1162584980-google-io
libprojects/abs/src/com/actionbarsherlock/view/SubMenu.java
Java
asf20
3,646
/* * Copyright (C) 2006 The Android Open Source Project * Copyright (C) 2011 Jake Wharton * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.actionbarsherlock.view; import android.content.Context; /** * <p>Abstract base class for a top-level window look and behavior policy. An * instance of this class should be used as the top-level view added to the * window manager. It provides standard UI policies such as a background, title * area, default key processing, etc.</p> * * <p>The only existing implementation of this abstract class is * android.policy.PhoneWindow, which you should instantiate when needing a * Window. Eventually that class will be refactored and a factory method added * for creating Window instances without knowing about a particular * implementation.</p> */ public abstract class Window extends android.view.Window { public static final long FEATURE_ACTION_BAR = android.view.Window.FEATURE_ACTION_BAR; public static final long FEATURE_ACTION_BAR_OVERLAY = android.view.Window.FEATURE_ACTION_BAR_OVERLAY; public static final long FEATURE_ACTION_MODE_OVERLAY = android.view.Window.FEATURE_ACTION_MODE_OVERLAY; public static final long FEATURE_NO_TITLE = android.view.Window.FEATURE_NO_TITLE; public static final long FEATURE_PROGRESS = android.view.Window.FEATURE_PROGRESS; public static final long FEATURE_INDETERMINATE_PROGRESS = android.view.Window.FEATURE_INDETERMINATE_PROGRESS; /** * Create a new instance for a context. * * @param context Context. */ private Window(Context context) { super(context); } public interface Callback { /** * Called when a panel's menu item has been selected by the user. * * @param featureId The panel that the menu is in. * @param item The menu item that was selected. * * @return boolean Return true to finish processing of selection, or * false to perform the normal menu handling (calling its * Runnable or sending a Message to its target Handler). */ public boolean onMenuItemSelected(int featureId, MenuItem item); } }
1162584980-google-io
libprojects/abs/src/com/actionbarsherlock/view/Window.java
Java
asf20
2,778
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.actionbarsherlock.view; import android.view.View; /** * Represents a contextual mode of the user interface. Action modes can be used for * modal interactions with content and replace parts of the normal UI until finished. * Examples of good action modes include selection modes, search, content editing, etc. */ public abstract class ActionMode { private Object mTag; /** * Set a tag object associated with this ActionMode. * * <p>Like the tag available to views, this allows applications to associate arbitrary * data with an ActionMode for later reference. * * @param tag Tag to associate with this ActionMode * * @see #getTag() */ public void setTag(Object tag) { mTag = tag; } /** * Retrieve the tag object associated with this ActionMode. * * <p>Like the tag available to views, this allows applications to associate arbitrary * data with an ActionMode for later reference. * * @return Tag associated with this ActionMode * * @see #setTag(Object) */ public Object getTag() { return mTag; } /** * Set the title of the action mode. This method will have no visible effect if * a custom view has been set. * * @param title Title string to set * * @see #setTitle(int) * @see #setCustomView(View) */ public abstract void setTitle(CharSequence title); /** * Set the title of the action mode. This method will have no visible effect if * a custom view has been set. * * @param resId Resource ID of a string to set as the title * * @see #setTitle(CharSequence) * @see #setCustomView(View) */ public abstract void setTitle(int resId); /** * Set the subtitle of the action mode. This method will have no visible effect if * a custom view has been set. * * @param subtitle Subtitle string to set * * @see #setSubtitle(int) * @see #setCustomView(View) */ public abstract void setSubtitle(CharSequence subtitle); /** * Set the subtitle of the action mode. This method will have no visible effect if * a custom view has been set. * * @param resId Resource ID of a string to set as the subtitle * * @see #setSubtitle(CharSequence) * @see #setCustomView(View) */ public abstract void setSubtitle(int resId); /** * Set a custom view for this action mode. The custom view will take the place of * the title and subtitle. Useful for things like search boxes. * * @param view Custom view to use in place of the title/subtitle. * * @see #setTitle(CharSequence) * @see #setSubtitle(CharSequence) */ public abstract void setCustomView(View view); /** * Invalidate the action mode and refresh menu content. The mode's * {@link ActionMode.Callback} will have its * {@link Callback#onPrepareActionMode(ActionMode, Menu)} method called. * If it returns true the menu will be scanned for updated content and any relevant changes * will be reflected to the user. */ public abstract void invalidate(); /** * Finish and close this action mode. The action mode's {@link ActionMode.Callback} will * have its {@link Callback#onDestroyActionMode(ActionMode)} method called. */ public abstract void finish(); /** * Returns the menu of actions that this action mode presents. * @return The action mode's menu. */ public abstract Menu getMenu(); /** * Returns the current title of this action mode. * @return Title text */ public abstract CharSequence getTitle(); /** * Returns the current subtitle of this action mode. * @return Subtitle text */ public abstract CharSequence getSubtitle(); /** * Returns the current custom view for this action mode. * @return The current custom view */ public abstract View getCustomView(); /** * Returns a {@link MenuInflater} with the ActionMode's context. */ public abstract MenuInflater getMenuInflater(); /** * Returns whether the UI presenting this action mode can take focus or not. * This is used by internal components within the framework that would otherwise * present an action mode UI that requires focus, such as an EditText as a custom view. * * @return true if the UI used to show this action mode can take focus * @hide Internal use only */ public boolean isUiFocusable() { return true; } /** * Callback interface for action modes. Supplied to * {@link View#startActionMode(Callback)}, a Callback * configures and handles events raised by a user's interaction with an action mode. * * <p>An action mode's lifecycle is as follows: * <ul> * <li>{@link Callback#onCreateActionMode(ActionMode, Menu)} once on initial * creation</li> * <li>{@link Callback#onPrepareActionMode(ActionMode, Menu)} after creation * and any time the {@link ActionMode} is invalidated</li> * <li>{@link Callback#onActionItemClicked(ActionMode, MenuItem)} any time a * contextual action button is clicked</li> * <li>{@link Callback#onDestroyActionMode(ActionMode)} when the action mode * is closed</li> * </ul> */ public interface Callback { /** * Called when action mode is first created. The menu supplied will be used to * generate action buttons for the action mode. * * @param mode ActionMode being created * @param menu Menu used to populate action buttons * @return true if the action mode should be created, false if entering this * mode should be aborted. */ public boolean onCreateActionMode(ActionMode mode, Menu menu); /** * Called to refresh an action mode's action menu whenever it is invalidated. * * @param mode ActionMode being prepared * @param menu Menu used to populate action buttons * @return true if the menu or action mode was updated, false otherwise. */ public boolean onPrepareActionMode(ActionMode mode, Menu menu); /** * Called to report a user click on an action button. * * @param mode The current ActionMode * @param item The item that was clicked * @return true if this callback handled the event, false if the standard MenuItem * invocation should continue. */ public boolean onActionItemClicked(ActionMode mode, MenuItem item); /** * Called when an action mode is about to be exited and destroyed. * * @param mode The current ActionMode being destroyed */ public void onDestroyActionMode(ActionMode mode); } }
1162584980-google-io
libprojects/abs/src/com/actionbarsherlock/view/ActionMode.java
Java
asf20
7,820
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.actionbarsherlock.view; import android.content.Context; import android.view.View; /** * This class is a mediator for accomplishing a given task, for example sharing a file. * It is responsible for creating a view that performs an action that accomplishes the task. * This class also implements other functions such a performing a default action. * <p> * An ActionProvider can be optionally specified for a {@link MenuItem} and in such a * case it will be responsible for creating the action view that appears in the * {@link android.app.ActionBar} as a substitute for the menu item when the item is * displayed as an action item. Also the provider is responsible for performing a * default action if a menu item placed on the overflow menu of the ActionBar is * selected and none of the menu item callbacks has handled the selection. For this * case the provider can also optionally provide a sub-menu for accomplishing the * task at hand. * </p> * <p> * There are two ways for using an action provider for creating and handling of action views: * <ul> * <li> * Setting the action provider on a {@link MenuItem} directly by calling * {@link MenuItem#setActionProvider(ActionProvider)}. * </li> * <li> * Declaring the action provider in the menu XML resource. For example: * <pre> * <code> * &lt;item android:id="@+id/my_menu_item" * android:title="Title" * android:icon="@drawable/my_menu_item_icon" * android:showAsAction="ifRoom" * android:actionProviderClass="foo.bar.SomeActionProvider" /&gt; * </code> * </pre> * </li> * </ul> * </p> * * @see MenuItem#setActionProvider(ActionProvider) * @see MenuItem#getActionProvider() */ public abstract class ActionProvider { private SubUiVisibilityListener mSubUiVisibilityListener; /** * Creates a new instance. * * @param context Context for accessing resources. */ public ActionProvider(Context context) { } /** * Factory method for creating new action views. * * @return A new action view. */ public abstract View onCreateActionView(); /** * Performs an optional default action. * <p> * For the case of an action provider placed in a menu item not shown as an action this * method is invoked if previous callbacks for processing menu selection has handled * the event. * </p> * <p> * A menu item selection is processed in the following order: * <ul> * <li> * Receiving a call to {@link MenuItem.OnMenuItemClickListener#onMenuItemClick * MenuItem.OnMenuItemClickListener.onMenuItemClick}. * </li> * <li> * Receiving a call to {@link android.app.Activity#onOptionsItemSelected(MenuItem) * Activity.onOptionsItemSelected(MenuItem)} * </li> * <li> * Receiving a call to {@link android.app.Fragment#onOptionsItemSelected(MenuItem) * Fragment.onOptionsItemSelected(MenuItem)} * </li> * <li> * Launching the {@link android.content.Intent} set via * {@link MenuItem#setIntent(android.content.Intent) MenuItem.setIntent(android.content.Intent)} * </li> * <li> * Invoking this method. * </li> * </ul> * </p> * <p> * The default implementation does not perform any action and returns false. * </p> */ public boolean onPerformDefaultAction() { return false; } /** * Determines if this ActionProvider has a submenu associated with it. * * <p>Associated submenus will be shown when an action view is not. This * provider instance will receive a call to {@link #onPrepareSubMenu(SubMenu)} * after the call to {@link #onPerformDefaultAction()} and before a submenu is * displayed to the user. * * @return true if the item backed by this provider should have an associated submenu */ public boolean hasSubMenu() { return false; } /** * Called to prepare an associated submenu for the menu item backed by this ActionProvider. * * <p>if {@link #hasSubMenu()} returns true, this method will be called when the * menu item is selected to prepare the submenu for presentation to the user. Apps * may use this to create or alter submenu content right before display. * * @param subMenu Submenu that will be displayed */ public void onPrepareSubMenu(SubMenu subMenu) { } /** * Notify the system that the visibility of an action view's sub-UI such as * an anchored popup has changed. This will affect how other system * visibility notifications occur. * * @hide Pending future API approval */ public void subUiVisibilityChanged(boolean isVisible) { if (mSubUiVisibilityListener != null) { mSubUiVisibilityListener.onSubUiVisibilityChanged(isVisible); } } /** * @hide Internal use only */ public void setSubUiVisibilityListener(SubUiVisibilityListener listener) { mSubUiVisibilityListener = listener; } /** * @hide Internal use only */ public interface SubUiVisibilityListener { public void onSubUiVisibilityChanged(boolean isVisible); } }
1162584980-google-io
libprojects/abs/src/com/actionbarsherlock/view/ActionProvider.java
Java
asf20
5,865
package com.actionbarsherlock; import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Iterator; import android.app.Activity; import android.content.Context; import android.content.res.Configuration; import android.os.Build; import android.os.Bundle; import android.util.DisplayMetrics; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; import android.view.Window; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.internal.ActionBarSherlockCompat; import com.actionbarsherlock.internal.ActionBarSherlockNative; import com.actionbarsherlock.view.ActionMode; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; /** * <p>Helper for implementing the action bar design pattern across all versions * of Android.</p> * * <p>This class will manage interaction with a custom action bar based on the * Android 4.0 source code. The exposed API mirrors that of its native * counterpart and you should refer to its documentation for instruction.</p> * * @author Jake Wharton <jakewharton@gmail.com> */ public abstract class ActionBarSherlock { protected static final String TAG = "ActionBarSherlock"; protected static final boolean DEBUG = false; private static final Class<?>[] CONSTRUCTOR_ARGS = new Class[] { Activity.class, int.class }; private static final HashMap<Implementation, Class<? extends ActionBarSherlock>> IMPLEMENTATIONS = new HashMap<Implementation, Class<? extends ActionBarSherlock>>(); static { //Register our two built-in implementations registerImplementation(ActionBarSherlockCompat.class); registerImplementation(ActionBarSherlockNative.class); } /** * <p>Denotes an implementation of ActionBarSherlock which provides an * action bar-enhanced experience.</p> */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface Implementation { static final int DEFAULT_API = -1; static final int DEFAULT_DPI = -1; int api() default DEFAULT_API; int dpi() default DEFAULT_DPI; } /** Activity interface for menu creation callback. */ public interface OnCreatePanelMenuListener { public boolean onCreatePanelMenu(int featureId, Menu menu); } /** Activity interface for menu creation callback. */ public interface OnCreateOptionsMenuListener { public boolean onCreateOptionsMenu(Menu menu); } /** Activity interface for menu item selection callback. */ public interface OnMenuItemSelectedListener { public boolean onMenuItemSelected(int featureId, MenuItem item); } /** Activity interface for menu item selection callback. */ public interface OnOptionsItemSelectedListener { public boolean onOptionsItemSelected(MenuItem item); } /** Activity interface for menu preparation callback. */ public interface OnPreparePanelListener { public boolean onPreparePanel(int featureId, View view, Menu menu); } /** Activity interface for menu preparation callback. */ public interface OnPrepareOptionsMenuListener { public boolean onPrepareOptionsMenu(Menu menu); } /** Activity interface for action mode finished callback. */ public interface OnActionModeFinishedListener { public void onActionModeFinished(ActionMode mode); } /** Activity interface for action mode started callback. */ public interface OnActionModeStartedListener { public void onActionModeStarted(ActionMode mode); } /** * If set, the logic in these classes will assume that an {@link Activity} * is dispatching all of the required events to the class. This flag should * only be used internally or if you are creating your own base activity * modeled after one of the included types (e.g., {@code SherlockActivity}). */ public static final int FLAG_DELEGATE = 1; /** * Register an ActionBarSherlock implementation. * * @param implementationClass Target implementation class which extends * {@link ActionBarSherlock}. This class must also be annotated with * {@link Implementation}. */ public static void registerImplementation(Class<? extends ActionBarSherlock> implementationClass) { if (!implementationClass.isAnnotationPresent(Implementation.class)) { throw new IllegalArgumentException("Class " + implementationClass.getSimpleName() + " is not annotated with @Implementation"); } else if (IMPLEMENTATIONS.containsValue(implementationClass)) { if (DEBUG) Log.w(TAG, "Class " + implementationClass.getSimpleName() + " already registered"); return; } Implementation impl = implementationClass.getAnnotation(Implementation.class); if (DEBUG) Log.i(TAG, "Registering " + implementationClass.getSimpleName() + " with qualifier " + impl); IMPLEMENTATIONS.put(impl, implementationClass); } /** * Unregister an ActionBarSherlock implementation. <strong>This should be * considered very volatile and you should only use it if you know what * you are doing.</strong> You have been warned. * * @param implementationClass Target implementation class. * @return Boolean indicating whether the class was removed. */ public static boolean unregisterImplementation(Class<? extends ActionBarSherlock> implementationClass) { return IMPLEMENTATIONS.values().remove(implementationClass); } /** * Wrap an activity with an action bar abstraction which will enable the * use of a custom implementation on platforms where a native version does * not exist. * * @param activity Activity to wrap. * @return Instance to interact with the action bar. */ public static ActionBarSherlock wrap(Activity activity) { return wrap(activity, 0); } /** * Wrap an activity with an action bar abstraction which will enable the * use of a custom implementation on platforms where a native version does * not exist. * * @param activity Owning activity. * @param flags Option flags to control behavior. * @return Instance to interact with the action bar. */ public static ActionBarSherlock wrap(Activity activity, int flags) { //Create a local implementation map we can modify HashMap<Implementation, Class<? extends ActionBarSherlock>> impls = new HashMap<Implementation, Class<? extends ActionBarSherlock>>(IMPLEMENTATIONS); boolean hasQualfier; /* DPI FILTERING */ hasQualfier = false; for (Implementation key : impls.keySet()) { //Only honor TVDPI as a specific qualifier if (key.dpi() == DisplayMetrics.DENSITY_TV) { hasQualfier = true; break; } } if (hasQualfier) { final boolean isTvDpi = activity.getResources().getDisplayMetrics().densityDpi == DisplayMetrics.DENSITY_TV; for (Iterator<Implementation> keys = impls.keySet().iterator(); keys.hasNext(); ) { int keyDpi = keys.next().dpi(); if ((isTvDpi && keyDpi != DisplayMetrics.DENSITY_TV) || (!isTvDpi && keyDpi == DisplayMetrics.DENSITY_TV)) { keys.remove(); } } } /* API FILTERING */ hasQualfier = false; for (Implementation key : impls.keySet()) { if (key.api() != Implementation.DEFAULT_API) { hasQualfier = true; break; } } if (hasQualfier) { final int runtimeApi = Build.VERSION.SDK_INT; int bestApi = 0; for (Iterator<Implementation> keys = impls.keySet().iterator(); keys.hasNext(); ) { int keyApi = keys.next().api(); if (keyApi > runtimeApi) { keys.remove(); } else if (keyApi > bestApi) { bestApi = keyApi; } } for (Iterator<Implementation> keys = impls.keySet().iterator(); keys.hasNext(); ) { if (keys.next().api() != bestApi) { keys.remove(); } } } if (impls.size() > 1) { throw new IllegalStateException("More than one implementation matches configuration."); } if (impls.isEmpty()) { throw new IllegalStateException("No implementations match configuration."); } Class<? extends ActionBarSherlock> impl = impls.values().iterator().next(); if (DEBUG) Log.i(TAG, "Using implementation: " + impl.getSimpleName()); try { Constructor<? extends ActionBarSherlock> ctor = impl.getConstructor(CONSTRUCTOR_ARGS); return ctor.newInstance(activity, flags); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } /** Activity which is displaying the action bar. Also used for context. */ protected final Activity mActivity; /** Whether delegating actions for the activity or managing ourselves. */ protected final boolean mIsDelegate; /** Reference to our custom menu inflater which supports action items. */ protected MenuInflater mMenuInflater; protected ActionBarSherlock(Activity activity, int flags) { if (DEBUG) Log.d(TAG, "[<ctor>] activity: " + activity + ", flags: " + flags); mActivity = activity; mIsDelegate = (flags & FLAG_DELEGATE) != 0; } /** * Get the current action bar instance. * * @return Action bar instance. */ public abstract ActionBar getActionBar(); /////////////////////////////////////////////////////////////////////////// // Lifecycle and interaction callbacks when delegating /////////////////////////////////////////////////////////////////////////// /** * Notify action bar of a configuration change event. Should be dispatched * after the call to the superclass implementation. * * <blockquote><pre> * @Override * public void onConfigurationChanged(Configuration newConfig) { * super.onConfigurationChanged(newConfig); * mSherlock.dispatchConfigurationChanged(newConfig); * } * </pre></blockquote> * * @param newConfig The new device configuration. */ public void dispatchConfigurationChanged(Configuration newConfig) {} /** * Notify the action bar that the activity has finished its resuming. This * should be dispatched after the call to the superclass implementation. * * <blockquote><pre> * @Override * protected void onPostResume() { * super.onPostResume(); * mSherlock.dispatchPostResume(); * } * </pre></blockquote> */ public void dispatchPostResume() {} /** * Notify the action bar that the activity is pausing. This should be * dispatched before the call to the superclass implementation. * * <blockquote><pre> * @Override * protected void onPause() { * mSherlock.dispatchPause(); * super.onPause(); * } * </pre></blockquote> */ public void dispatchPause() {} /** * Notify the action bar that the activity is stopping. This should be * called before the superclass implementation. * * <blockquote><p> * @Override * protected void onStop() { * mSherlock.dispatchStop(); * super.onStop(); * } * </p></blockquote> */ public void dispatchStop() {} /** * Indicate that the menu should be recreated by calling * {@link OnCreateOptionsMenuListener#onCreateOptionsMenu(com.actionbarsherlock.view.Menu)}. */ public abstract void dispatchInvalidateOptionsMenu(); /** * Notify the action bar that it should display its overflow menu if it is * appropriate for the device. The implementation should conditionally * call the superclass method only if this method returns {@code false}. * * <blockquote><p> * @Override * public void openOptionsMenu() { * if (!mSherlock.dispatchOpenOptionsMenu()) { * super.openOptionsMenu(); * } * } * </p></blockquote> * * @return {@code true} if the opening of the menu was handled internally. */ public boolean dispatchOpenOptionsMenu() { return false; } /** * Notify the action bar that it should close its overflow menu if it is * appropriate for the device. This implementation should conditionally * call the superclass method only if this method returns {@code false}. * * <blockquote><pre> * @Override * public void closeOptionsMenu() { * if (!mSherlock.dispatchCloseOptionsMenu()) { * super.closeOptionsMenu(); * } * } * </pre></blockquote> * * @return {@code true} if the closing of the menu was handled internally. */ public boolean dispatchCloseOptionsMenu() { return false; } /** * Notify the class that the activity has finished its creation. This * should be called after the superclass implementation. * * <blockquote><pre> * @Override * protected void onPostCreate(Bundle savedInstanceState) { * mSherlock.dispatchPostCreate(savedInstanceState); * super.onPostCreate(savedInstanceState); * } * </pre></blockquote> * * @param savedInstanceState If the activity is being re-initialized after * previously being shut down then this Bundle * contains the data it most recently supplied in * {@link Activity#}onSaveInstanceState(Bundle)}. * <strong>Note: Otherwise it is null.</strong> */ public void dispatchPostCreate(Bundle savedInstanceState) {} /** * Notify the action bar that the title has changed and the action bar * should be updated to reflect the change. This should be called before * the superclass implementation. * * <blockquote><pre> * @Override * protected void onTitleChanged(CharSequence title, int color) { * mSherlock.dispatchTitleChanged(title, color); * super.onTitleChanged(title, color); * } * </pre></blockquote> * * @param title New activity title. * @param color New activity color. */ public void dispatchTitleChanged(CharSequence title, int color) {} /** * Notify the action bar the user has created a key event. This is used to * toggle the display of the overflow action item with the menu key and to * close the action mode or expanded action item with the back key. * * <blockquote><pre> * @Override * public boolean dispatchKeyEvent(KeyEvent event) { * if (mSherlock.dispatchKeyEvent(event)) { * return true; * } * return super.dispatchKeyEvent(event); * } * </pre></blockquote> * * @param event Description of the key event. * @return {@code true} if the event was handled. */ public boolean dispatchKeyEvent(KeyEvent event) { return false; } /** * Notify the action bar that the Activity has triggered a menu creation * which should happen on the conclusion of {@link Activity#onCreate}. This * will be used to gain a reference to the native menu for native and * overflow binding as well as to indicate when compatibility create should * occur for the first time. * * @param menu Activity native menu. * @return {@code true} since we always want to say that we have a native */ public abstract boolean dispatchCreateOptionsMenu(android.view.Menu menu); /** * Notify the action bar that the Activity has triggered a menu preparation * which usually means that the user has requested the overflow menu via a * hardware menu key. You should return the result of this method call and * not call the superclass implementation. * * <blockquote><p> * @Override * public final boolean onPrepareOptionsMenu(android.view.Menu menu) { * return mSherlock.dispatchPrepareOptionsMenu(menu); * } * </p></blockquote> * * @param menu Activity native menu. * @return {@code true} if menu display should proceed. */ public abstract boolean dispatchPrepareOptionsMenu(android.view.Menu menu); /** * Notify the action bar that a native options menu item has been selected. * The implementation should return the result of this method call. * * <blockquote><p> * @Override * public final boolean onOptionsItemSelected(android.view.MenuItem item) { * return mSherlock.dispatchOptionsItemSelected(item); * } * </p></blockquote> * * @param item Options menu item. * @return @{code true} if the selection was handled. */ public abstract boolean dispatchOptionsItemSelected(android.view.MenuItem item); /** * Notify the action bar that the overflow menu has been opened. The * implementation should conditionally return {@code true} if this method * returns {@code true}, otherwise return the result of the superclass * method. * * <blockquote><p> * @Override * public final boolean onMenuOpened(int featureId, android.view.Menu menu) { * if (mSherlock.dispatchMenuOpened(featureId, menu)) { * return true; * } * return super.onMenuOpened(featureId, menu); * } * </p></blockquote> * * @param featureId Window feature which triggered the event. * @param menu Activity native menu. * @return {@code true} if the event was handled by this method. */ public boolean dispatchMenuOpened(int featureId, android.view.Menu menu) { return false; } /** * Notify the action bar that the overflow menu has been closed. This * method should be called before the superclass implementation. * * <blockquote><p> * @Override * public void onPanelClosed(int featureId, android.view.Menu menu) { * mSherlock.dispatchPanelClosed(featureId, menu); * super.onPanelClosed(featureId, menu); * } * </p></blockquote> * * @param featureId * @param menu */ public void dispatchPanelClosed(int featureId, android.view.Menu menu) {} /** * Notify the action bar that the activity has been destroyed. This method * should be called before the superclass implementation. * * <blockquote><p> * @Override * public void onDestroy() { * mSherlock.dispatchDestroy(); * super.onDestroy(); * } * </p></blockquote> */ public void dispatchDestroy() {} /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// /** * Internal method to trigger the menu creation process. * * @return {@code true} if menu creation should proceed. */ protected final boolean callbackCreateOptionsMenu(Menu menu) { if (DEBUG) Log.d(TAG, "[callbackCreateOptionsMenu] menu: " + menu); boolean result = true; if (mActivity instanceof OnCreatePanelMenuListener) { OnCreatePanelMenuListener listener = (OnCreatePanelMenuListener)mActivity; result = listener.onCreatePanelMenu(Window.FEATURE_OPTIONS_PANEL, menu); } else if (mActivity instanceof OnCreateOptionsMenuListener) { OnCreateOptionsMenuListener listener = (OnCreateOptionsMenuListener)mActivity; result = listener.onCreateOptionsMenu(menu); } if (DEBUG) Log.d(TAG, "[callbackCreateOptionsMenu] returning " + result); return result; } /** * Internal method to trigger the menu preparation process. * * @return {@code true} if menu preparation should proceed. */ protected final boolean callbackPrepareOptionsMenu(Menu menu) { if (DEBUG) Log.d(TAG, "[callbackPrepareOptionsMenu] menu: " + menu); boolean result = true; if (mActivity instanceof OnPreparePanelListener) { OnPreparePanelListener listener = (OnPreparePanelListener)mActivity; result = listener.onPreparePanel(Window.FEATURE_OPTIONS_PANEL, null, menu); } else if (mActivity instanceof OnPrepareOptionsMenuListener) { OnPrepareOptionsMenuListener listener = (OnPrepareOptionsMenuListener)mActivity; result = listener.onPrepareOptionsMenu(menu); } if (DEBUG) Log.d(TAG, "[callbackPrepareOptionsMenu] returning " + result); return result; } /** * Internal method for dispatching options menu selection to the owning * activity callback. * * @param item Selected options menu item. * @return {@code true} if the item selection was handled in the callback. */ protected final boolean callbackOptionsItemSelected(MenuItem item) { if (DEBUG) Log.d(TAG, "[callbackOptionsItemSelected] item: " + item.getTitleCondensed()); boolean result = false; if (mActivity instanceof OnMenuItemSelectedListener) { OnMenuItemSelectedListener listener = (OnMenuItemSelectedListener)mActivity; result = listener.onMenuItemSelected(Window.FEATURE_OPTIONS_PANEL, item); } else if (mActivity instanceof OnOptionsItemSelectedListener) { OnOptionsItemSelectedListener listener = (OnOptionsItemSelectedListener)mActivity; result = listener.onOptionsItemSelected(item); } if (DEBUG) Log.d(TAG, "[callbackOptionsItemSelected] returning " + result); return result; } /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// /** * Query for the availability of a certain feature. * * @param featureId The feature ID to check. * @return {@code true} if feature is enabled, {@code false} otherwise. */ public abstract boolean hasFeature(int featureId); /** * Enable extended screen features. This must be called before * {@code setContentView()}. May be called as many times as desired as long * as it is before {@code setContentView()}. If not called, no extended * features will be available. You can not turn off a feature once it is * requested. * * @param featureId The desired features, defined as constants by Window. * @return Returns true if the requested feature is supported and now * enabled. */ public abstract boolean requestFeature(int featureId); /** * Set extra options that will influence the UI for this window. * * @param uiOptions Flags specifying extra options for this window. */ public abstract void setUiOptions(int uiOptions); /** * Set extra options that will influence the UI for this window. Only the * bits filtered by mask will be modified. * * @param uiOptions Flags specifying extra options for this window. * @param mask Flags specifying which options should be modified. Others * will remain unchanged. */ public abstract void setUiOptions(int uiOptions, int mask); /** * Set the content of the activity inside the action bar. * * @param layoutResId Layout resource ID. */ public abstract void setContentView(int layoutResId); /** * Set the content of the activity inside the action bar. * * @param view The desired content to display. */ public void setContentView(View view) { if (DEBUG) Log.d(TAG, "[setContentView] view: " + view); setContentView(view, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT)); } /** * Set the content of the activity inside the action bar. * * @param view The desired content to display. * @param params Layout parameters to apply to the view. */ public abstract void setContentView(View view, ViewGroup.LayoutParams params); /** * Variation on {@link #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)} * to add an additional content view to the screen. Added after any * existing ones on the screen -- existing views are NOT removed. * * @param view The desired content to display. * @param params Layout parameters for the view. */ public abstract void addContentView(View view, ViewGroup.LayoutParams params); /** * Change the title associated with this activity. */ public abstract void setTitle(CharSequence title); /** * Change the title associated with this activity. */ public void setTitle(int resId) { if (DEBUG) Log.d(TAG, "[setTitle] resId: " + resId); setTitle(mActivity.getString(resId)); } /** * Sets the visibility of the progress bar in the title. * <p> * In order for the progress bar to be shown, the feature must be requested * via {@link #requestWindowFeature(int)}. * * @param visible Whether to show the progress bars in the title. */ public abstract void setProgressBarVisibility(boolean visible); /** * Sets the visibility of the indeterminate progress bar in the title. * <p> * In order for the progress bar to be shown, the feature must be requested * via {@link #requestWindowFeature(int)}. * * @param visible Whether to show the progress bars in the title. */ public abstract void setProgressBarIndeterminateVisibility(boolean visible); /** * Sets whether the horizontal progress bar in the title should be indeterminate (the circular * is always indeterminate). * <p> * In order for the progress bar to be shown, the feature must be requested * via {@link #requestWindowFeature(int)}. * * @param indeterminate Whether the horizontal progress bar should be indeterminate. */ public abstract void setProgressBarIndeterminate(boolean indeterminate); /** * Sets the progress for the progress bars in the title. * <p> * In order for the progress bar to be shown, the feature must be requested * via {@link #requestWindowFeature(int)}. * * @param progress The progress for the progress bar. Valid ranges are from * 0 to 10000 (both inclusive). If 10000 is given, the progress * bar will be completely filled and will fade out. */ public abstract void setProgress(int progress); /** * Sets the secondary progress for the progress bar in the title. This * progress is drawn between the primary progress (set via * {@link #setProgress(int)} and the background. It can be ideal for media * scenarios such as showing the buffering progress while the default * progress shows the play progress. * <p> * In order for the progress bar to be shown, the feature must be requested * via {@link #requestWindowFeature(int)}. * * @param secondaryProgress The secondary progress for the progress bar. Valid ranges are from * 0 to 10000 (both inclusive). */ public abstract void setSecondaryProgress(int secondaryProgress); /** * Get a menu inflater instance which supports the newer menu attributes. * * @return Menu inflater instance. */ public MenuInflater getMenuInflater() { if (DEBUG) Log.d(TAG, "[getMenuInflater]"); // Make sure that action views can get an appropriate theme. if (mMenuInflater == null) { if (getActionBar() != null) { mMenuInflater = new MenuInflater(getThemedContext()); } else { mMenuInflater = new MenuInflater(mActivity); } } return mMenuInflater; } protected abstract Context getThemedContext(); /** * Start an action mode. * * @param callback Callback that will manage lifecycle events for this * context mode. * @return The ContextMode that was started, or null if it was canceled. * @see ActionMode */ public abstract ActionMode startActionMode(ActionMode.Callback callback); }
1162584980-google-io
libprojects/abs/src/com/actionbarsherlock/ActionBarSherlock.java
Java
asf20
30,369
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.actionbarsherlock.internal.nineoldandroids.animation; import java.util.ArrayList; import android.view.animation.Interpolator; import com.actionbarsherlock.internal.nineoldandroids.animation.Keyframe.FloatKeyframe; /** * This class holds a collection of FloatKeyframe objects and is called by ValueAnimator to calculate * values between those keyframes for a given animation. The class internal to the animation * package because it is an implementation detail of how Keyframes are stored and used. * * <p>This type-specific subclass of KeyframeSet, along with the other type-specific subclass for * int, exists to speed up the getValue() method when there is no custom * TypeEvaluator set for the animation, so that values can be calculated without autoboxing to the * Object equivalents of these primitive types.</p> */ @SuppressWarnings("unchecked") class FloatKeyframeSet extends KeyframeSet { private float firstValue; private float lastValue; private float deltaValue; private boolean firstTime = true; public FloatKeyframeSet(FloatKeyframe... keyframes) { super(keyframes); } @Override public Object getValue(float fraction) { return getFloatValue(fraction); } @Override public FloatKeyframeSet clone() { ArrayList<Keyframe> keyframes = mKeyframes; int numKeyframes = mKeyframes.size(); FloatKeyframe[] newKeyframes = new FloatKeyframe[numKeyframes]; for (int i = 0; i < numKeyframes; ++i) { newKeyframes[i] = (FloatKeyframe) keyframes.get(i).clone(); } FloatKeyframeSet newSet = new FloatKeyframeSet(newKeyframes); return newSet; } public float getFloatValue(float fraction) { if (mNumKeyframes == 2) { if (firstTime) { firstTime = false; firstValue = ((FloatKeyframe) mKeyframes.get(0)).getFloatValue(); lastValue = ((FloatKeyframe) mKeyframes.get(1)).getFloatValue(); deltaValue = lastValue - firstValue; } if (mInterpolator != null) { fraction = mInterpolator.getInterpolation(fraction); } if (mEvaluator == null) { return firstValue + fraction * deltaValue; } else { return ((Number)mEvaluator.evaluate(fraction, firstValue, lastValue)).floatValue(); } } if (fraction <= 0f) { final FloatKeyframe prevKeyframe = (FloatKeyframe) mKeyframes.get(0); final FloatKeyframe nextKeyframe = (FloatKeyframe) mKeyframes.get(1); float prevValue = prevKeyframe.getFloatValue(); float nextValue = nextKeyframe.getFloatValue(); float prevFraction = prevKeyframe.getFraction(); float nextFraction = nextKeyframe.getFraction(); final /*Time*/Interpolator interpolator = nextKeyframe.getInterpolator(); if (interpolator != null) { fraction = interpolator.getInterpolation(fraction); } float intervalFraction = (fraction - prevFraction) / (nextFraction - prevFraction); return mEvaluator == null ? prevValue + intervalFraction * (nextValue - prevValue) : ((Number)mEvaluator.evaluate(intervalFraction, prevValue, nextValue)). floatValue(); } else if (fraction >= 1f) { final FloatKeyframe prevKeyframe = (FloatKeyframe) mKeyframes.get(mNumKeyframes - 2); final FloatKeyframe nextKeyframe = (FloatKeyframe) mKeyframes.get(mNumKeyframes - 1); float prevValue = prevKeyframe.getFloatValue(); float nextValue = nextKeyframe.getFloatValue(); float prevFraction = prevKeyframe.getFraction(); float nextFraction = nextKeyframe.getFraction(); final /*Time*/Interpolator interpolator = nextKeyframe.getInterpolator(); if (interpolator != null) { fraction = interpolator.getInterpolation(fraction); } float intervalFraction = (fraction - prevFraction) / (nextFraction - prevFraction); return mEvaluator == null ? prevValue + intervalFraction * (nextValue - prevValue) : ((Number)mEvaluator.evaluate(intervalFraction, prevValue, nextValue)). floatValue(); } FloatKeyframe prevKeyframe = (FloatKeyframe) mKeyframes.get(0); for (int i = 1; i < mNumKeyframes; ++i) { FloatKeyframe nextKeyframe = (FloatKeyframe) mKeyframes.get(i); if (fraction < nextKeyframe.getFraction()) { final /*Time*/Interpolator interpolator = nextKeyframe.getInterpolator(); if (interpolator != null) { fraction = interpolator.getInterpolation(fraction); } float intervalFraction = (fraction - prevKeyframe.getFraction()) / (nextKeyframe.getFraction() - prevKeyframe.getFraction()); float prevValue = prevKeyframe.getFloatValue(); float nextValue = nextKeyframe.getFloatValue(); return mEvaluator == null ? prevValue + intervalFraction * (nextValue - prevValue) : ((Number)mEvaluator.evaluate(intervalFraction, prevValue, nextValue)). floatValue(); } prevKeyframe = nextKeyframe; } // shouldn't get here return ((Number)mKeyframes.get(mNumKeyframes - 1).getValue()).floatValue(); } }
1162584980-google-io
libprojects/abs/src/com/actionbarsherlock/internal/nineoldandroids/animation/FloatKeyframeSet.java
Java
asf20
6,312
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.actionbarsherlock.internal.nineoldandroids.animation; /** * This evaluator can be used to perform type interpolation between <code>int</code> values. */ public class IntEvaluator implements TypeEvaluator<Integer> { /** * This function returns the result of linearly interpolating the start and end values, with * <code>fraction</code> representing the proportion between the start and end values. The * calculation is a simple parametric calculation: <code>result = x0 + t * (v1 - v0)</code>, * where <code>x0</code> is <code>startValue</code>, <code>x1</code> is <code>endValue</code>, * and <code>t</code> is <code>fraction</code>. * * @param fraction The fraction from the starting to the ending values * @param startValue The start value; should be of type <code>int</code> or * <code>Integer</code> * @param endValue The end value; should be of type <code>int</code> or <code>Integer</code> * @return A linear interpolation between the start and end values, given the * <code>fraction</code> parameter. */ public Integer evaluate(float fraction, Integer startValue, Integer endValue) { int startInt = startValue; return (int)(startInt + fraction * (endValue - startInt)); } }
1162584980-google-io
libprojects/abs/src/com/actionbarsherlock/internal/nineoldandroids/animation/IntEvaluator.java
Java
asf20
1,940
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.actionbarsherlock.internal.nineoldandroids.animation; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.util.AndroidRuntimeException; import android.view.animation.AccelerateDecelerateInterpolator; import android.view.animation.AnimationUtils; import android.view.animation.Interpolator; import android.view.animation.LinearInterpolator; import java.util.ArrayList; import java.util.HashMap; /** * This class provides a simple timing engine for running animations * which calculate animated values and set them on target objects. * * <p>There is a single timing pulse that all animations use. It runs in a * custom handler to ensure that property changes happen on the UI thread.</p> * * <p>By default, ValueAnimator uses non-linear time interpolation, via the * {@link AccelerateDecelerateInterpolator} class, which accelerates into and decelerates * out of an animation. This behavior can be changed by calling * {@link ValueAnimator#setInterpolator(TimeInterpolator)}.</p> */ @SuppressWarnings({"rawtypes", "unchecked"}) public class ValueAnimator extends Animator { /** * Internal constants */ /* * The default amount of time in ms between animation frames */ private static final long DEFAULT_FRAME_DELAY = 10; /** * Messages sent to timing handler: START is sent when an animation first begins, FRAME is sent * by the handler to itself to process the next animation frame */ static final int ANIMATION_START = 0; static final int ANIMATION_FRAME = 1; /** * Values used with internal variable mPlayingState to indicate the current state of an * animation. */ static final int STOPPED = 0; // Not yet playing static final int RUNNING = 1; // Playing normally static final int SEEKED = 2; // Seeked to some time value /** * Internal variables * NOTE: This object implements the clone() method, making a deep copy of any referenced * objects. As other non-trivial fields are added to this class, make sure to add logic * to clone() to make deep copies of them. */ // The first time that the animation's animateFrame() method is called. This time is used to // determine elapsed time (and therefore the elapsed fraction) in subsequent calls // to animateFrame() long mStartTime; /** * Set when setCurrentPlayTime() is called. If negative, animation is not currently seeked * to a value. */ long mSeekTime = -1; // TODO: We access the following ThreadLocal variables often, some of them on every update. // If ThreadLocal access is significantly expensive, we may want to put all of these // fields into a structure sot hat we just access ThreadLocal once to get the reference // to that structure, then access the structure directly for each field. // The static sAnimationHandler processes the internal timing loop on which all animations // are based private static ThreadLocal<AnimationHandler> sAnimationHandler = new ThreadLocal<AnimationHandler>(); // The per-thread list of all active animations private static final ThreadLocal<ArrayList<ValueAnimator>> sAnimations = new ThreadLocal<ArrayList<ValueAnimator>>() { @Override protected ArrayList<ValueAnimator> initialValue() { return new ArrayList<ValueAnimator>(); } }; // The per-thread set of animations to be started on the next animation frame private static final ThreadLocal<ArrayList<ValueAnimator>> sPendingAnimations = new ThreadLocal<ArrayList<ValueAnimator>>() { @Override protected ArrayList<ValueAnimator> initialValue() { return new ArrayList<ValueAnimator>(); } }; /** * Internal per-thread collections used to avoid set collisions as animations start and end * while being processed. */ private static final ThreadLocal<ArrayList<ValueAnimator>> sDelayedAnims = new ThreadLocal<ArrayList<ValueAnimator>>() { @Override protected ArrayList<ValueAnimator> initialValue() { return new ArrayList<ValueAnimator>(); } }; private static final ThreadLocal<ArrayList<ValueAnimator>> sEndingAnims = new ThreadLocal<ArrayList<ValueAnimator>>() { @Override protected ArrayList<ValueAnimator> initialValue() { return new ArrayList<ValueAnimator>(); } }; private static final ThreadLocal<ArrayList<ValueAnimator>> sReadyAnims = new ThreadLocal<ArrayList<ValueAnimator>>() { @Override protected ArrayList<ValueAnimator> initialValue() { return new ArrayList<ValueAnimator>(); } }; // The time interpolator to be used if none is set on the animation private static final /*Time*/Interpolator sDefaultInterpolator = new AccelerateDecelerateInterpolator(); // type evaluators for the primitive types handled by this implementation //private static final TypeEvaluator sIntEvaluator = new IntEvaluator(); //private static final TypeEvaluator sFloatEvaluator = new FloatEvaluator(); /** * Used to indicate whether the animation is currently playing in reverse. This causes the * elapsed fraction to be inverted to calculate the appropriate values. */ private boolean mPlayingBackwards = false; /** * This variable tracks the current iteration that is playing. When mCurrentIteration exceeds the * repeatCount (if repeatCount!=INFINITE), the animation ends */ private int mCurrentIteration = 0; /** * Tracks current elapsed/eased fraction, for querying in getAnimatedFraction(). */ private float mCurrentFraction = 0f; /** * Tracks whether a startDelay'd animation has begun playing through the startDelay. */ private boolean mStartedDelay = false; /** * Tracks the time at which the animation began playing through its startDelay. This is * different from the mStartTime variable, which is used to track when the animation became * active (which is when the startDelay expired and the animation was added to the active * animations list). */ private long mDelayStartTime; /** * Flag that represents the current state of the animation. Used to figure out when to start * an animation (if state == STOPPED). Also used to end an animation that * has been cancel()'d or end()'d since the last animation frame. Possible values are * STOPPED, RUNNING, SEEKED. */ int mPlayingState = STOPPED; /** * Additional playing state to indicate whether an animator has been start()'d. There is * some lag between a call to start() and the first animation frame. We should still note * that the animation has been started, even if it's first animation frame has not yet * happened, and reflect that state in isRunning(). * Note that delayed animations are different: they are not started until their first * animation frame, which occurs after their delay elapses. */ private boolean mRunning = false; /** * Additional playing state to indicate whether an animator has been start()'d, whether or * not there is a nonzero startDelay. */ private boolean mStarted = false; /** * Flag that denotes whether the animation is set up and ready to go. Used to * set up animation that has not yet been started. */ boolean mInitialized = false; // // Backing variables // // How long the animation should last in ms private long mDuration = 300; // The amount of time in ms to delay starting the animation after start() is called private long mStartDelay = 0; // The number of milliseconds between animation frames private static long sFrameDelay = DEFAULT_FRAME_DELAY; // The number of times the animation will repeat. The default is 0, which means the animation // will play only once private int mRepeatCount = 0; /** * The type of repetition that will occur when repeatMode is nonzero. RESTART means the * animation will start from the beginning on every new cycle. REVERSE means the animation * will reverse directions on each iteration. */ private int mRepeatMode = RESTART; /** * The time interpolator to be used. The elapsed fraction of the animation will be passed * through this interpolator to calculate the interpolated fraction, which is then used to * calculate the animated values. */ private /*Time*/Interpolator mInterpolator = sDefaultInterpolator; /** * The set of listeners to be sent events through the life of an animation. */ private ArrayList<AnimatorUpdateListener> mUpdateListeners = null; /** * The property/value sets being animated. */ PropertyValuesHolder[] mValues; /** * A hashmap of the PropertyValuesHolder objects. This map is used to lookup animated values * by property name during calls to getAnimatedValue(String). */ HashMap<String, PropertyValuesHolder> mValuesMap; /** * Public constants */ /** * When the animation reaches the end and <code>repeatCount</code> is INFINITE * or a positive value, the animation restarts from the beginning. */ public static final int RESTART = 1; /** * When the animation reaches the end and <code>repeatCount</code> is INFINITE * or a positive value, the animation reverses direction on every iteration. */ public static final int REVERSE = 2; /** * This value used used with the {@link #setRepeatCount(int)} property to repeat * the animation indefinitely. */ public static final int INFINITE = -1; /** * Creates a new ValueAnimator object. This default constructor is primarily for * use internally; the factory methods which take parameters are more generally * useful. */ public ValueAnimator() { } /** * Constructs and returns a ValueAnimator that animates between int values. A single * value implies that that value is the one being animated to. However, this is not typically * useful in a ValueAnimator object because there is no way for the object to determine the * starting value for the animation (unlike ObjectAnimator, which can derive that value * from the target object and property being animated). Therefore, there should typically * be two or more values. * * @param values A set of values that the animation will animate between over time. * @return A ValueAnimator object that is set up to animate between the given values. */ public static ValueAnimator ofInt(int... values) { ValueAnimator anim = new ValueAnimator(); anim.setIntValues(values); return anim; } /** * Constructs and returns a ValueAnimator that animates between float values. A single * value implies that that value is the one being animated to. However, this is not typically * useful in a ValueAnimator object because there is no way for the object to determine the * starting value for the animation (unlike ObjectAnimator, which can derive that value * from the target object and property being animated). Therefore, there should typically * be two or more values. * * @param values A set of values that the animation will animate between over time. * @return A ValueAnimator object that is set up to animate between the given values. */ public static ValueAnimator ofFloat(float... values) { ValueAnimator anim = new ValueAnimator(); anim.setFloatValues(values); return anim; } /** * Constructs and returns a ValueAnimator that animates between the values * specified in the PropertyValuesHolder objects. * * @param values A set of PropertyValuesHolder objects whose values will be animated * between over time. * @return A ValueAnimator object that is set up to animate between the given values. */ public static ValueAnimator ofPropertyValuesHolder(PropertyValuesHolder... values) { ValueAnimator anim = new ValueAnimator(); anim.setValues(values); return anim; } /** * Constructs and returns a ValueAnimator that animates between Object values. A single * value implies that that value is the one being animated to. However, this is not typically * useful in a ValueAnimator object because there is no way for the object to determine the * starting value for the animation (unlike ObjectAnimator, which can derive that value * from the target object and property being animated). Therefore, there should typically * be two or more values. * * <p>Since ValueAnimator does not know how to animate between arbitrary Objects, this * factory method also takes a TypeEvaluator object that the ValueAnimator will use * to perform that interpolation. * * @param evaluator A TypeEvaluator that will be called on each animation frame to * provide the ncessry interpolation between the Object values to derive the animated * value. * @param values A set of values that the animation will animate between over time. * @return A ValueAnimator object that is set up to animate between the given values. */ public static ValueAnimator ofObject(TypeEvaluator evaluator, Object... values) { ValueAnimator anim = new ValueAnimator(); anim.setObjectValues(values); anim.setEvaluator(evaluator); return anim; } /** * Sets int values that will be animated between. A single * value implies that that value is the one being animated to. However, this is not typically * useful in a ValueAnimator object because there is no way for the object to determine the * starting value for the animation (unlike ObjectAnimator, which can derive that value * from the target object and property being animated). Therefore, there should typically * be two or more values. * * <p>If there are already multiple sets of values defined for this ValueAnimator via more * than one PropertyValuesHolder object, this method will set the values for the first * of those objects.</p> * * @param values A set of values that the animation will animate between over time. */ public void setIntValues(int... values) { if (values == null || values.length == 0) { return; } if (mValues == null || mValues.length == 0) { setValues(new PropertyValuesHolder[]{PropertyValuesHolder.ofInt("", values)}); } else { PropertyValuesHolder valuesHolder = mValues[0]; valuesHolder.setIntValues(values); } // New property/values/target should cause re-initialization prior to starting mInitialized = false; } /** * Sets float values that will be animated between. A single * value implies that that value is the one being animated to. However, this is not typically * useful in a ValueAnimator object because there is no way for the object to determine the * starting value for the animation (unlike ObjectAnimator, which can derive that value * from the target object and property being animated). Therefore, there should typically * be two or more values. * * <p>If there are already multiple sets of values defined for this ValueAnimator via more * than one PropertyValuesHolder object, this method will set the values for the first * of those objects.</p> * * @param values A set of values that the animation will animate between over time. */ public void setFloatValues(float... values) { if (values == null || values.length == 0) { return; } if (mValues == null || mValues.length == 0) { setValues(new PropertyValuesHolder[]{PropertyValuesHolder.ofFloat("", values)}); } else { PropertyValuesHolder valuesHolder = mValues[0]; valuesHolder.setFloatValues(values); } // New property/values/target should cause re-initialization prior to starting mInitialized = false; } /** * Sets the values to animate between for this animation. A single * value implies that that value is the one being animated to. However, this is not typically * useful in a ValueAnimator object because there is no way for the object to determine the * starting value for the animation (unlike ObjectAnimator, which can derive that value * from the target object and property being animated). Therefore, there should typically * be two or more values. * * <p>If there are already multiple sets of values defined for this ValueAnimator via more * than one PropertyValuesHolder object, this method will set the values for the first * of those objects.</p> * * <p>There should be a TypeEvaluator set on the ValueAnimator that knows how to interpolate * between these value objects. ValueAnimator only knows how to interpolate between the * primitive types specified in the other setValues() methods.</p> * * @param values The set of values to animate between. */ public void setObjectValues(Object... values) { if (values == null || values.length == 0) { return; } if (mValues == null || mValues.length == 0) { setValues(new PropertyValuesHolder[]{PropertyValuesHolder.ofObject("", (TypeEvaluator)null, values)}); } else { PropertyValuesHolder valuesHolder = mValues[0]; valuesHolder.setObjectValues(values); } // New property/values/target should cause re-initialization prior to starting mInitialized = false; } /** * Sets the values, per property, being animated between. This function is called internally * by the constructors of ValueAnimator that take a list of values. But an ValueAnimator can * be constructed without values and this method can be called to set the values manually * instead. * * @param values The set of values, per property, being animated between. */ public void setValues(PropertyValuesHolder... values) { int numValues = values.length; mValues = values; mValuesMap = new HashMap<String, PropertyValuesHolder>(numValues); for (int i = 0; i < numValues; ++i) { PropertyValuesHolder valuesHolder = values[i]; mValuesMap.put(valuesHolder.getPropertyName(), valuesHolder); } // New property/values/target should cause re-initialization prior to starting mInitialized = false; } /** * Returns the values that this ValueAnimator animates between. These values are stored in * PropertyValuesHolder objects, even if the ValueAnimator was created with a simple list * of value objects instead. * * @return PropertyValuesHolder[] An array of PropertyValuesHolder objects which hold the * values, per property, that define the animation. */ public PropertyValuesHolder[] getValues() { return mValues; } /** * This function is called immediately before processing the first animation * frame of an animation. If there is a nonzero <code>startDelay</code>, the * function is called after that delay ends. * It takes care of the final initialization steps for the * animation. * * <p>Overrides of this method should call the superclass method to ensure * that internal mechanisms for the animation are set up correctly.</p> */ void initAnimation() { if (!mInitialized) { int numValues = mValues.length; for (int i = 0; i < numValues; ++i) { mValues[i].init(); } mInitialized = true; } } /** * Sets the length of the animation. The default duration is 300 milliseconds. * * @param duration The length of the animation, in milliseconds. This value cannot * be negative. * @return ValueAnimator The object called with setDuration(). This return * value makes it easier to compose statements together that construct and then set the * duration, as in <code>ValueAnimator.ofInt(0, 10).setDuration(500).start()</code>. */ public ValueAnimator setDuration(long duration) { if (duration < 0) { throw new IllegalArgumentException("Animators cannot have negative duration: " + duration); } mDuration = duration; return this; } /** * Gets the length of the animation. The default duration is 300 milliseconds. * * @return The length of the animation, in milliseconds. */ public long getDuration() { return mDuration; } /** * Sets the position of the animation to the specified point in time. This time should * be between 0 and the total duration of the animation, including any repetition. If * the animation has not yet been started, then it will not advance forward after it is * set to this time; it will simply set the time to this value and perform any appropriate * actions based on that time. If the animation is already running, then setCurrentPlayTime() * will set the current playing time to this value and continue playing from that point. * * @param playTime The time, in milliseconds, to which the animation is advanced or rewound. */ public void setCurrentPlayTime(long playTime) { initAnimation(); long currentTime = AnimationUtils.currentAnimationTimeMillis(); if (mPlayingState != RUNNING) { mSeekTime = playTime; mPlayingState = SEEKED; } mStartTime = currentTime - playTime; animationFrame(currentTime); } /** * Gets the current position of the animation in time, which is equal to the current * time minus the time that the animation started. An animation that is not yet started will * return a value of zero. * * @return The current position in time of the animation. */ public long getCurrentPlayTime() { if (!mInitialized || mPlayingState == STOPPED) { return 0; } return AnimationUtils.currentAnimationTimeMillis() - mStartTime; } /** * This custom, static handler handles the timing pulse that is shared by * all active animations. This approach ensures that the setting of animation * values will happen on the UI thread and that all animations will share * the same times for calculating their values, which makes synchronizing * animations possible. * */ private static class AnimationHandler extends Handler { /** * There are only two messages that we care about: ANIMATION_START and * ANIMATION_FRAME. The START message is sent when an animation's start() * method is called. It cannot start synchronously when start() is called * because the call may be on the wrong thread, and it would also not be * synchronized with other animations because it would not start on a common * timing pulse. So each animation sends a START message to the handler, which * causes the handler to place the animation on the active animations queue and * start processing frames for that animation. * The FRAME message is the one that is sent over and over while there are any * active animations to process. */ @Override public void handleMessage(Message msg) { boolean callAgain = true; ArrayList<ValueAnimator> animations = sAnimations.get(); ArrayList<ValueAnimator> delayedAnims = sDelayedAnims.get(); switch (msg.what) { // TODO: should we avoid sending frame message when starting if we // were already running? case ANIMATION_START: ArrayList<ValueAnimator> pendingAnimations = sPendingAnimations.get(); if (animations.size() > 0 || delayedAnims.size() > 0) { callAgain = false; } // pendingAnims holds any animations that have requested to be started // We're going to clear sPendingAnimations, but starting animation may // cause more to be added to the pending list (for example, if one animation // starting triggers another starting). So we loop until sPendingAnimations // is empty. while (pendingAnimations.size() > 0) { ArrayList<ValueAnimator> pendingCopy = (ArrayList<ValueAnimator>) pendingAnimations.clone(); pendingAnimations.clear(); int count = pendingCopy.size(); for (int i = 0; i < count; ++i) { ValueAnimator anim = pendingCopy.get(i); // If the animation has a startDelay, place it on the delayed list if (anim.mStartDelay == 0) { anim.startAnimation(); } else { delayedAnims.add(anim); } } } // fall through to process first frame of new animations case ANIMATION_FRAME: // currentTime holds the common time for all animations processed // during this frame long currentTime = AnimationUtils.currentAnimationTimeMillis(); ArrayList<ValueAnimator> readyAnims = sReadyAnims.get(); ArrayList<ValueAnimator> endingAnims = sEndingAnims.get(); // First, process animations currently sitting on the delayed queue, adding // them to the active animations if they are ready int numDelayedAnims = delayedAnims.size(); for (int i = 0; i < numDelayedAnims; ++i) { ValueAnimator anim = delayedAnims.get(i); if (anim.delayedAnimationFrame(currentTime)) { readyAnims.add(anim); } } int numReadyAnims = readyAnims.size(); if (numReadyAnims > 0) { for (int i = 0; i < numReadyAnims; ++i) { ValueAnimator anim = readyAnims.get(i); anim.startAnimation(); anim.mRunning = true; delayedAnims.remove(anim); } readyAnims.clear(); } // Now process all active animations. The return value from animationFrame() // tells the handler whether it should now be ended int numAnims = animations.size(); int i = 0; while (i < numAnims) { ValueAnimator anim = animations.get(i); if (anim.animationFrame(currentTime)) { endingAnims.add(anim); } if (animations.size() == numAnims) { ++i; } else { // An animation might be canceled or ended by client code // during the animation frame. Check to see if this happened by // seeing whether the current index is the same as it was before // calling animationFrame(). Another approach would be to copy // animations to a temporary list and process that list instead, // but that entails garbage and processing overhead that would // be nice to avoid. --numAnims; endingAnims.remove(anim); } } if (endingAnims.size() > 0) { for (i = 0; i < endingAnims.size(); ++i) { endingAnims.get(i).endAnimation(); } endingAnims.clear(); } // If there are still active or delayed animations, call the handler again // after the frameDelay if (callAgain && (!animations.isEmpty() || !delayedAnims.isEmpty())) { sendEmptyMessageDelayed(ANIMATION_FRAME, Math.max(0, sFrameDelay - (AnimationUtils.currentAnimationTimeMillis() - currentTime))); } break; } } } /** * The amount of time, in milliseconds, to delay starting the animation after * {@link #start()} is called. * * @return the number of milliseconds to delay running the animation */ public long getStartDelay() { return mStartDelay; } /** * The amount of time, in milliseconds, to delay starting the animation after * {@link #start()} is called. * @param startDelay The amount of the delay, in milliseconds */ public void setStartDelay(long startDelay) { this.mStartDelay = startDelay; } /** * The amount of time, in milliseconds, between each frame of the animation. This is a * requested time that the animation will attempt to honor, but the actual delay between * frames may be different, depending on system load and capabilities. This is a static * function because the same delay will be applied to all animations, since they are all * run off of a single timing loop. * * @return the requested time between frames, in milliseconds */ public static long getFrameDelay() { return sFrameDelay; } /** * The amount of time, in milliseconds, between each frame of the animation. This is a * requested time that the animation will attempt to honor, but the actual delay between * frames may be different, depending on system load and capabilities. This is a static * function because the same delay will be applied to all animations, since they are all * run off of a single timing loop. * * @param frameDelay the requested time between frames, in milliseconds */ public static void setFrameDelay(long frameDelay) { sFrameDelay = frameDelay; } /** * The most recent value calculated by this <code>ValueAnimator</code> when there is just one * property being animated. This value is only sensible while the animation is running. The main * purpose for this read-only property is to retrieve the value from the <code>ValueAnimator</code> * during a call to {@link AnimatorUpdateListener#onAnimationUpdate(ValueAnimator)}, which * is called during each animation frame, immediately after the value is calculated. * * @return animatedValue The value most recently calculated by this <code>ValueAnimator</code> for * the single property being animated. If there are several properties being animated * (specified by several PropertyValuesHolder objects in the constructor), this function * returns the animated value for the first of those objects. */ public Object getAnimatedValue() { if (mValues != null && mValues.length > 0) { return mValues[0].getAnimatedValue(); } // Shouldn't get here; should always have values unless ValueAnimator was set up wrong return null; } /** * The most recent value calculated by this <code>ValueAnimator</code> for <code>propertyName</code>. * The main purpose for this read-only property is to retrieve the value from the * <code>ValueAnimator</code> during a call to * {@link AnimatorUpdateListener#onAnimationUpdate(ValueAnimator)}, which * is called during each animation frame, immediately after the value is calculated. * * @return animatedValue The value most recently calculated for the named property * by this <code>ValueAnimator</code>. */ public Object getAnimatedValue(String propertyName) { PropertyValuesHolder valuesHolder = mValuesMap.get(propertyName); if (valuesHolder != null) { return valuesHolder.getAnimatedValue(); } else { // At least avoid crashing if called with bogus propertyName return null; } } /** * Sets how many times the animation should be repeated. If the repeat * count is 0, the animation is never repeated. If the repeat count is * greater than 0 or {@link #INFINITE}, the repeat mode will be taken * into account. The repeat count is 0 by default. * * @param value the number of times the animation should be repeated */ public void setRepeatCount(int value) { mRepeatCount = value; } /** * Defines how many times the animation should repeat. The default value * is 0. * * @return the number of times the animation should repeat, or {@link #INFINITE} */ public int getRepeatCount() { return mRepeatCount; } /** * Defines what this animation should do when it reaches the end. This * setting is applied only when the repeat count is either greater than * 0 or {@link #INFINITE}. Defaults to {@link #RESTART}. * * @param value {@link #RESTART} or {@link #REVERSE} */ public void setRepeatMode(int value) { mRepeatMode = value; } /** * Defines what this animation should do when it reaches the end. * * @return either one of {@link #REVERSE} or {@link #RESTART} */ public int getRepeatMode() { return mRepeatMode; } /** * Adds a listener to the set of listeners that are sent update events through the life of * an animation. This method is called on all listeners for every frame of the animation, * after the values for the animation have been calculated. * * @param listener the listener to be added to the current set of listeners for this animation. */ public void addUpdateListener(AnimatorUpdateListener listener) { if (mUpdateListeners == null) { mUpdateListeners = new ArrayList<AnimatorUpdateListener>(); } mUpdateListeners.add(listener); } /** * Removes all listeners from the set listening to frame updates for this animation. */ public void removeAllUpdateListeners() { if (mUpdateListeners == null) { return; } mUpdateListeners.clear(); mUpdateListeners = null; } /** * Removes a listener from the set listening to frame updates for this animation. * * @param listener the listener to be removed from the current set of update listeners * for this animation. */ public void removeUpdateListener(AnimatorUpdateListener listener) { if (mUpdateListeners == null) { return; } mUpdateListeners.remove(listener); if (mUpdateListeners.size() == 0) { mUpdateListeners = null; } } /** * The time interpolator used in calculating the elapsed fraction of this animation. The * interpolator determines whether the animation runs with linear or non-linear motion, * such as acceleration and deceleration. The default value is * {@link android.view.animation.AccelerateDecelerateInterpolator} * * @param value the interpolator to be used by this animation. A value of <code>null</code> * will result in linear interpolation. */ @Override public void setInterpolator(/*Time*/Interpolator value) { if (value != null) { mInterpolator = value; } else { mInterpolator = new LinearInterpolator(); } } /** * Returns the timing interpolator that this ValueAnimator uses. * * @return The timing interpolator for this ValueAnimator. */ public /*Time*/Interpolator getInterpolator() { return mInterpolator; } /** * The type evaluator to be used when calculating the animated values of this animation. * The system will automatically assign a float or int evaluator based on the type * of <code>startValue</code> and <code>endValue</code> in the constructor. But if these values * are not one of these primitive types, or if different evaluation is desired (such as is * necessary with int values that represent colors), a custom evaluator needs to be assigned. * For example, when running an animation on color values, the {@link ArgbEvaluator} * should be used to get correct RGB color interpolation. * * <p>If this ValueAnimator has only one set of values being animated between, this evaluator * will be used for that set. If there are several sets of values being animated, which is * the case if PropertyValuesHOlder objects were set on the ValueAnimator, then the evaluator * is assigned just to the first PropertyValuesHolder object.</p> * * @param value the evaluator to be used this animation */ public void setEvaluator(TypeEvaluator value) { if (value != null && mValues != null && mValues.length > 0) { mValues[0].setEvaluator(value); } } /** * Start the animation playing. This version of start() takes a boolean flag that indicates * whether the animation should play in reverse. The flag is usually false, but may be set * to true if called from the reverse() method. * * <p>The animation started by calling this method will be run on the thread that called * this method. This thread should have a Looper on it (a runtime exception will be thrown if * this is not the case). Also, if the animation will animate * properties of objects in the view hierarchy, then the calling thread should be the UI * thread for that view hierarchy.</p> * * @param playBackwards Whether the ValueAnimator should start playing in reverse. */ private void start(boolean playBackwards) { if (Looper.myLooper() == null) { throw new AndroidRuntimeException("Animators may only be run on Looper threads"); } mPlayingBackwards = playBackwards; mCurrentIteration = 0; mPlayingState = STOPPED; mStarted = true; mStartedDelay = false; sPendingAnimations.get().add(this); if (mStartDelay == 0) { // This sets the initial value of the animation, prior to actually starting it running setCurrentPlayTime(getCurrentPlayTime()); mPlayingState = STOPPED; mRunning = true; if (mListeners != null) { ArrayList<AnimatorListener> tmpListeners = (ArrayList<AnimatorListener>) mListeners.clone(); int numListeners = tmpListeners.size(); for (int i = 0; i < numListeners; ++i) { tmpListeners.get(i).onAnimationStart(this); } } } AnimationHandler animationHandler = sAnimationHandler.get(); if (animationHandler == null) { animationHandler = new AnimationHandler(); sAnimationHandler.set(animationHandler); } animationHandler.sendEmptyMessage(ANIMATION_START); } @Override public void start() { start(false); } @Override public void cancel() { // Only cancel if the animation is actually running or has been started and is about // to run if (mPlayingState != STOPPED || sPendingAnimations.get().contains(this) || sDelayedAnims.get().contains(this)) { // Only notify listeners if the animator has actually started if (mRunning && mListeners != null) { ArrayList<AnimatorListener> tmpListeners = (ArrayList<AnimatorListener>) mListeners.clone(); for (AnimatorListener listener : tmpListeners) { listener.onAnimationCancel(this); } } endAnimation(); } } @Override public void end() { if (!sAnimations.get().contains(this) && !sPendingAnimations.get().contains(this)) { // Special case if the animation has not yet started; get it ready for ending mStartedDelay = false; startAnimation(); } else if (!mInitialized) { initAnimation(); } // The final value set on the target varies, depending on whether the animation // was supposed to repeat an odd number of times if (mRepeatCount > 0 && (mRepeatCount & 0x01) == 1) { animateValue(0f); } else { animateValue(1f); } endAnimation(); } @Override public boolean isRunning() { return (mPlayingState == RUNNING || mRunning); } @Override public boolean isStarted() { return mStarted; } /** * Plays the ValueAnimator in reverse. If the animation is already running, * it will stop itself and play backwards from the point reached when reverse was called. * If the animation is not currently running, then it will start from the end and * play backwards. This behavior is only set for the current animation; future playing * of the animation will use the default behavior of playing forward. */ public void reverse() { mPlayingBackwards = !mPlayingBackwards; if (mPlayingState == RUNNING) { long currentTime = AnimationUtils.currentAnimationTimeMillis(); long currentPlayTime = currentTime - mStartTime; long timeLeft = mDuration - currentPlayTime; mStartTime = currentTime - timeLeft; } else { start(true); } } /** * Called internally to end an animation by removing it from the animations list. Must be * called on the UI thread. */ private void endAnimation() { sAnimations.get().remove(this); sPendingAnimations.get().remove(this); sDelayedAnims.get().remove(this); mPlayingState = STOPPED; if (mRunning && mListeners != null) { ArrayList<AnimatorListener> tmpListeners = (ArrayList<AnimatorListener>) mListeners.clone(); int numListeners = tmpListeners.size(); for (int i = 0; i < numListeners; ++i) { tmpListeners.get(i).onAnimationEnd(this); } } mRunning = false; mStarted = false; } /** * Called internally to start an animation by adding it to the active animations list. Must be * called on the UI thread. */ private void startAnimation() { initAnimation(); sAnimations.get().add(this); if (mStartDelay > 0 && mListeners != null) { // Listeners were already notified in start() if startDelay is 0; this is // just for delayed animations ArrayList<AnimatorListener> tmpListeners = (ArrayList<AnimatorListener>) mListeners.clone(); int numListeners = tmpListeners.size(); for (int i = 0; i < numListeners; ++i) { tmpListeners.get(i).onAnimationStart(this); } } } /** * Internal function called to process an animation frame on an animation that is currently * sleeping through its <code>startDelay</code> phase. The return value indicates whether it * should be woken up and put on the active animations queue. * * @param currentTime The current animation time, used to calculate whether the animation * has exceeded its <code>startDelay</code> and should be started. * @return True if the animation's <code>startDelay</code> has been exceeded and the animation * should be added to the set of active animations. */ private boolean delayedAnimationFrame(long currentTime) { if (!mStartedDelay) { mStartedDelay = true; mDelayStartTime = currentTime; } else { long deltaTime = currentTime - mDelayStartTime; if (deltaTime > mStartDelay) { // startDelay ended - start the anim and record the // mStartTime appropriately mStartTime = currentTime - (deltaTime - mStartDelay); mPlayingState = RUNNING; return true; } } return false; } /** * This internal function processes a single animation frame for a given animation. The * currentTime parameter is the timing pulse sent by the handler, used to calculate the * elapsed duration, and therefore * the elapsed fraction, of the animation. The return value indicates whether the animation * should be ended (which happens when the elapsed time of the animation exceeds the * animation's duration, including the repeatCount). * * @param currentTime The current time, as tracked by the static timing handler * @return true if the animation's duration, including any repetitions due to * <code>repeatCount</code> has been exceeded and the animation should be ended. */ boolean animationFrame(long currentTime) { boolean done = false; if (mPlayingState == STOPPED) { mPlayingState = RUNNING; if (mSeekTime < 0) { mStartTime = currentTime; } else { mStartTime = currentTime - mSeekTime; // Now that we're playing, reset the seek time mSeekTime = -1; } } switch (mPlayingState) { case RUNNING: case SEEKED: float fraction = mDuration > 0 ? (float)(currentTime - mStartTime) / mDuration : 1f; if (fraction >= 1f) { if (mCurrentIteration < mRepeatCount || mRepeatCount == INFINITE) { // Time to repeat if (mListeners != null) { int numListeners = mListeners.size(); for (int i = 0; i < numListeners; ++i) { mListeners.get(i).onAnimationRepeat(this); } } if (mRepeatMode == REVERSE) { mPlayingBackwards = mPlayingBackwards ? false : true; } mCurrentIteration += (int)fraction; fraction = fraction % 1f; mStartTime += mDuration; } else { done = true; fraction = Math.min(fraction, 1.0f); } } if (mPlayingBackwards) { fraction = 1f - fraction; } animateValue(fraction); break; } return done; } /** * Returns the current animation fraction, which is the elapsed/interpolated fraction used in * the most recent frame update on the animation. * * @return Elapsed/interpolated fraction of the animation. */ public float getAnimatedFraction() { return mCurrentFraction; } /** * This method is called with the elapsed fraction of the animation during every * animation frame. This function turns the elapsed fraction into an interpolated fraction * and then into an animated value (from the evaluator. The function is called mostly during * animation updates, but it is also called when the <code>end()</code> * function is called, to set the final value on the property. * * <p>Overrides of this method must call the superclass to perform the calculation * of the animated value.</p> * * @param fraction The elapsed fraction of the animation. */ void animateValue(float fraction) { fraction = mInterpolator.getInterpolation(fraction); mCurrentFraction = fraction; int numValues = mValues.length; for (int i = 0; i < numValues; ++i) { mValues[i].calculateValue(fraction); } if (mUpdateListeners != null) { int numListeners = mUpdateListeners.size(); for (int i = 0; i < numListeners; ++i) { mUpdateListeners.get(i).onAnimationUpdate(this); } } } @Override public ValueAnimator clone() { final ValueAnimator anim = (ValueAnimator) super.clone(); if (mUpdateListeners != null) { ArrayList<AnimatorUpdateListener> oldListeners = mUpdateListeners; anim.mUpdateListeners = new ArrayList<AnimatorUpdateListener>(); int numListeners = oldListeners.size(); for (int i = 0; i < numListeners; ++i) { anim.mUpdateListeners.add(oldListeners.get(i)); } } anim.mSeekTime = -1; anim.mPlayingBackwards = false; anim.mCurrentIteration = 0; anim.mInitialized = false; anim.mPlayingState = STOPPED; anim.mStartedDelay = false; PropertyValuesHolder[] oldValues = mValues; if (oldValues != null) { int numValues = oldValues.length; anim.mValues = new PropertyValuesHolder[numValues]; anim.mValuesMap = new HashMap<String, PropertyValuesHolder>(numValues); for (int i = 0; i < numValues; ++i) { PropertyValuesHolder newValuesHolder = oldValues[i].clone(); anim.mValues[i] = newValuesHolder; anim.mValuesMap.put(newValuesHolder.getPropertyName(), newValuesHolder); } } return anim; } /** * Implementors of this interface can add themselves as update listeners * to an <code>ValueAnimator</code> instance to receive callbacks on every animation * frame, after the current frame's values have been calculated for that * <code>ValueAnimator</code>. */ public static interface AnimatorUpdateListener { /** * <p>Notifies the occurrence of another frame of the animation.</p> * * @param animation The animation which was repeated. */ void onAnimationUpdate(ValueAnimator animation); } /** * Return the number of animations currently running. * * Used by StrictMode internally to annotate violations. Only * called on the main thread. * * @hide */ public static int getCurrentAnimationsCount() { return sAnimations.get().size(); } /** * Clear all animations on this thread, without canceling or ending them. * This should be used with caution. * * @hide */ public static void clearAllAnimations() { sAnimations.get().clear(); sPendingAnimations.get().clear(); sDelayedAnims.get().clear(); } @Override public String toString() { String returnVal = "ValueAnimator@" + Integer.toHexString(hashCode()); if (mValues != null) { for (int i = 0; i < mValues.length; ++i) { returnVal += "\n " + mValues[i].toString(); } } return returnVal; } }
1162584980-google-io
libprojects/abs/src/com/actionbarsherlock/internal/nineoldandroids/animation/ValueAnimator.java
Java
asf20
53,216
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.actionbarsherlock.internal.nineoldandroids.animation; import java.util.ArrayList; import android.view.animation.Interpolator; /** * This is the superclass for classes which provide basic support for animations which can be * started, ended, and have <code>AnimatorListeners</code> added to them. */ public abstract class Animator implements Cloneable { /** * The set of listeners to be sent events through the life of an animation. */ ArrayList<AnimatorListener> mListeners = null; /** * Starts this animation. If the animation has a nonzero startDelay, the animation will start * running after that delay elapses. A non-delayed animation will have its initial * value(s) set immediately, followed by calls to * {@link AnimatorListener#onAnimationStart(Animator)} for any listeners of this animator. * * <p>The animation started by calling this method will be run on the thread that called * this method. This thread should have a Looper on it (a runtime exception will be thrown if * this is not the case). Also, if the animation will animate * properties of objects in the view hierarchy, then the calling thread should be the UI * thread for that view hierarchy.</p> * */ public void start() { } /** * Cancels the animation. Unlike {@link #end()}, <code>cancel()</code> causes the animation to * stop in its tracks, sending an * {@link android.animation.Animator.AnimatorListener#onAnimationCancel(Animator)} to * its listeners, followed by an * {@link android.animation.Animator.AnimatorListener#onAnimationEnd(Animator)} message. * * <p>This method must be called on the thread that is running the animation.</p> */ public void cancel() { } /** * Ends the animation. This causes the animation to assign the end value of the property being * animated, then calling the * {@link android.animation.Animator.AnimatorListener#onAnimationEnd(Animator)} method on * its listeners. * * <p>This method must be called on the thread that is running the animation.</p> */ public void end() { } /** * The amount of time, in milliseconds, to delay starting the animation after * {@link #start()} is called. * * @return the number of milliseconds to delay running the animation */ public abstract long getStartDelay(); /** * The amount of time, in milliseconds, to delay starting the animation after * {@link #start()} is called. * @param startDelay The amount of the delay, in milliseconds */ public abstract void setStartDelay(long startDelay); /** * Sets the length of the animation. * * @param duration The length of the animation, in milliseconds. */ public abstract Animator setDuration(long duration); /** * Gets the length of the animation. * * @return The length of the animation, in milliseconds. */ public abstract long getDuration(); /** * The time interpolator used in calculating the elapsed fraction of this animation. The * interpolator determines whether the animation runs with linear or non-linear motion, * such as acceleration and deceleration. The default value is * {@link android.view.animation.AccelerateDecelerateInterpolator} * * @param value the interpolator to be used by this animation */ public abstract void setInterpolator(/*Time*/Interpolator value); /** * Returns whether this Animator is currently running (having been started and gone past any * initial startDelay period and not yet ended). * * @return Whether the Animator is running. */ public abstract boolean isRunning(); /** * Returns whether this Animator has been started and not yet ended. This state is a superset * of the state of {@link #isRunning()}, because an Animator with a nonzero * {@link #getStartDelay() startDelay} will return true for {@link #isStarted()} during the * delay phase, whereas {@link #isRunning()} will return true only after the delay phase * is complete. * * @return Whether the Animator has been started and not yet ended. */ public boolean isStarted() { // Default method returns value for isRunning(). Subclasses should override to return a // real value. return isRunning(); } /** * Adds a listener to the set of listeners that are sent events through the life of an * animation, such as start, repeat, and end. * * @param listener the listener to be added to the current set of listeners for this animation. */ public void addListener(AnimatorListener listener) { if (mListeners == null) { mListeners = new ArrayList<AnimatorListener>(); } mListeners.add(listener); } /** * Removes a listener from the set listening to this animation. * * @param listener the listener to be removed from the current set of listeners for this * animation. */ public void removeListener(AnimatorListener listener) { if (mListeners == null) { return; } mListeners.remove(listener); if (mListeners.size() == 0) { mListeners = null; } } /** * Gets the set of {@link android.animation.Animator.AnimatorListener} objects that are currently * listening for events on this <code>Animator</code> object. * * @return ArrayList<AnimatorListener> The set of listeners. */ public ArrayList<AnimatorListener> getListeners() { return mListeners; } /** * Removes all listeners from this object. This is equivalent to calling * <code>getListeners()</code> followed by calling <code>clear()</code> on the * returned list of listeners. */ public void removeAllListeners() { if (mListeners != null) { mListeners.clear(); mListeners = null; } } @Override public Animator clone() { try { final Animator anim = (Animator) super.clone(); if (mListeners != null) { ArrayList<AnimatorListener> oldListeners = mListeners; anim.mListeners = new ArrayList<AnimatorListener>(); int numListeners = oldListeners.size(); for (int i = 0; i < numListeners; ++i) { anim.mListeners.add(oldListeners.get(i)); } } return anim; } catch (CloneNotSupportedException e) { throw new AssertionError(); } } /** * This method tells the object to use appropriate information to extract * starting values for the animation. For example, a AnimatorSet object will pass * this call to its child objects to tell them to set up the values. A * ObjectAnimator object will use the information it has about its target object * and PropertyValuesHolder objects to get the start values for its properties. * An ValueAnimator object will ignore the request since it does not have enough * information (such as a target object) to gather these values. */ public void setupStartValues() { } /** * This method tells the object to use appropriate information to extract * ending values for the animation. For example, a AnimatorSet object will pass * this call to its child objects to tell them to set up the values. A * ObjectAnimator object will use the information it has about its target object * and PropertyValuesHolder objects to get the start values for its properties. * An ValueAnimator object will ignore the request since it does not have enough * information (such as a target object) to gather these values. */ public void setupEndValues() { } /** * Sets the target object whose property will be animated by this animation. Not all subclasses * operate on target objects (for example, {@link ValueAnimator}, but this method * is on the superclass for the convenience of dealing generically with those subclasses * that do handle targets. * * @param target The object being animated */ public void setTarget(Object target) { } /** * <p>An animation listener receives notifications from an animation. * Notifications indicate animation related events, such as the end or the * repetition of the animation.</p> */ public static interface AnimatorListener { /** * <p>Notifies the start of the animation.</p> * * @param animation The started animation. */ void onAnimationStart(Animator animation); /** * <p>Notifies the end of the animation. This callback is not invoked * for animations with repeat count set to INFINITE.</p> * * @param animation The animation which reached its end. */ void onAnimationEnd(Animator animation); /** * <p>Notifies the cancellation of the animation. This callback is not invoked * for animations with repeat count set to INFINITE.</p> * * @param animation The animation which was canceled. */ void onAnimationCancel(Animator animation); /** * <p>Notifies the repetition of the animation.</p> * * @param animation The animation which was repeated. */ void onAnimationRepeat(Animator animation); } }
1162584980-google-io
libprojects/abs/src/com/actionbarsherlock/internal/nineoldandroids/animation/Animator.java
Java
asf20
10,313
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.actionbarsherlock.internal.nineoldandroids.animation; import android.util.Log; //import android.util.Property; //import java.lang.reflect.Method; import java.util.ArrayList; /** * This subclass of {@link ValueAnimator} provides support for animating properties on target objects. * The constructors of this class take parameters to define the target object that will be animated * as well as the name of the property that will be animated. Appropriate set/get functions * are then determined internally and the animation will call these functions as necessary to * animate the property. * * @see #setPropertyName(String) * */ @SuppressWarnings("rawtypes") public final class ObjectAnimator extends ValueAnimator { private static final boolean DBG = false; // The target object on which the property exists, set in the constructor private Object mTarget; private String mPropertyName; //private Property mProperty; /** * Sets the name of the property that will be animated. This name is used to derive * a setter function that will be called to set animated values. * For example, a property name of <code>foo</code> will result * in a call to the function <code>setFoo()</code> on the target object. If either * <code>valueFrom</code> or <code>valueTo</code> is null, then a getter function will * also be derived and called. * * <p>For best performance of the mechanism that calls the setter function determined by the * name of the property being animated, use <code>float</code> or <code>int</code> typed values, * and make the setter function for those properties have a <code>void</code> return value. This * will cause the code to take an optimized path for these constrained circumstances. Other * property types and return types will work, but will have more overhead in processing * the requests due to normal reflection mechanisms.</p> * * <p>Note that the setter function derived from this property name * must take the same parameter type as the * <code>valueFrom</code> and <code>valueTo</code> properties, otherwise the call to * the setter function will fail.</p> * * <p>If this ObjectAnimator has been set up to animate several properties together, * using more than one PropertyValuesHolder objects, then setting the propertyName simply * sets the propertyName in the first of those PropertyValuesHolder objects.</p> * * @param propertyName The name of the property being animated. Should not be null. */ public void setPropertyName(String propertyName) { // mValues could be null if this is being constructed piecemeal. Just record the // propertyName to be used later when setValues() is called if so. if (mValues != null) { PropertyValuesHolder valuesHolder = mValues[0]; String oldName = valuesHolder.getPropertyName(); valuesHolder.setPropertyName(propertyName); mValuesMap.remove(oldName); mValuesMap.put(propertyName, valuesHolder); } mPropertyName = propertyName; // New property/values/target should cause re-initialization prior to starting mInitialized = false; } /** * Sets the property that will be animated. Property objects will take precedence over * properties specified by the {@link #setPropertyName(String)} method. Animations should * be set up to use one or the other, not both. * * @param property The property being animated. Should not be null. */ //public void setProperty(Property property) { // // mValues could be null if this is being constructed piecemeal. Just record the // // propertyName to be used later when setValues() is called if so. // if (mValues != null) { // PropertyValuesHolder valuesHolder = mValues[0]; // String oldName = valuesHolder.getPropertyName(); // valuesHolder.setProperty(property); // mValuesMap.remove(oldName); // mValuesMap.put(mPropertyName, valuesHolder); // } // if (mProperty != null) { // mPropertyName = property.getName(); // } // mProperty = property; // // New property/values/target should cause re-initialization prior to starting // mInitialized = false; //} /** * Gets the name of the property that will be animated. This name will be used to derive * a setter function that will be called to set animated values. * For example, a property name of <code>foo</code> will result * in a call to the function <code>setFoo()</code> on the target object. If either * <code>valueFrom</code> or <code>valueTo</code> is null, then a getter function will * also be derived and called. */ public String getPropertyName() { return mPropertyName; } /** * Creates a new ObjectAnimator object. This default constructor is primarily for * use internally; the other constructors which take parameters are more generally * useful. */ public ObjectAnimator() { } /** * Private utility constructor that initializes the target object and name of the * property being animated. * * @param target The object whose property is to be animated. This object should * have a public method on it called <code>setName()</code>, where <code>name</code> is * the value of the <code>propertyName</code> parameter. * @param propertyName The name of the property being animated. */ private ObjectAnimator(Object target, String propertyName) { mTarget = target; setPropertyName(propertyName); } /** * Private utility constructor that initializes the target object and property being animated. * * @param target The object whose property is to be animated. * @param property The property being animated. */ //private <T> ObjectAnimator(T target, Property<T, ?> property) { // mTarget = target; // setProperty(property); //} /** * Constructs and returns an ObjectAnimator that animates between int values. A single * value implies that that value is the one being animated to. Two values imply a starting * and ending values. More than two values imply a starting value, values to animate through * along the way, and an ending value (these values will be distributed evenly across * the duration of the animation). * * @param target The object whose property is to be animated. This object should * have a public method on it called <code>setName()</code>, where <code>name</code> is * the value of the <code>propertyName</code> parameter. * @param propertyName The name of the property being animated. * @param values A set of values that the animation will animate between over time. * @return An ObjectAnimator object that is set up to animate between the given values. */ public static ObjectAnimator ofInt(Object target, String propertyName, int... values) { ObjectAnimator anim = new ObjectAnimator(target, propertyName); anim.setIntValues(values); return anim; } /** * Constructs and returns an ObjectAnimator that animates between int values. A single * value implies that that value is the one being animated to. Two values imply a starting * and ending values. More than two values imply a starting value, values to animate through * along the way, and an ending value (these values will be distributed evenly across * the duration of the animation). * * @param target The object whose property is to be animated. * @param property The property being animated. * @param values A set of values that the animation will animate between over time. * @return An ObjectAnimator object that is set up to animate between the given values. */ //public static <T> ObjectAnimator ofInt(T target, Property<T, Integer> property, int... values) { // ObjectAnimator anim = new ObjectAnimator(target, property); // anim.setIntValues(values); // return anim; //} /** * Constructs and returns an ObjectAnimator that animates between float values. A single * value implies that that value is the one being animated to. Two values imply a starting * and ending values. More than two values imply a starting value, values to animate through * along the way, and an ending value (these values will be distributed evenly across * the duration of the animation). * * @param target The object whose property is to be animated. This object should * have a public method on it called <code>setName()</code>, where <code>name</code> is * the value of the <code>propertyName</code> parameter. * @param propertyName The name of the property being animated. * @param values A set of values that the animation will animate between over time. * @return An ObjectAnimator object that is set up to animate between the given values. */ public static ObjectAnimator ofFloat(Object target, String propertyName, float... values) { ObjectAnimator anim = new ObjectAnimator(target, propertyName); anim.setFloatValues(values); return anim; } /** * Constructs and returns an ObjectAnimator that animates between float values. A single * value implies that that value is the one being animated to. Two values imply a starting * and ending values. More than two values imply a starting value, values to animate through * along the way, and an ending value (these values will be distributed evenly across * the duration of the animation). * * @param target The object whose property is to be animated. * @param property The property being animated. * @param values A set of values that the animation will animate between over time. * @return An ObjectAnimator object that is set up to animate between the given values. */ //public static <T> ObjectAnimator ofFloat(T target, Property<T, Float> property, // float... values) { // ObjectAnimator anim = new ObjectAnimator(target, property); // anim.setFloatValues(values); // return anim; //} /** * Constructs and returns an ObjectAnimator that animates between Object values. A single * value implies that that value is the one being animated to. Two values imply a starting * and ending values. More than two values imply a starting value, values to animate through * along the way, and an ending value (these values will be distributed evenly across * the duration of the animation). * * @param target The object whose property is to be animated. This object should * have a public method on it called <code>setName()</code>, where <code>name</code> is * the value of the <code>propertyName</code> parameter. * @param propertyName The name of the property being animated. * @param evaluator A TypeEvaluator that will be called on each animation frame to * provide the necessary interpolation between the Object values to derive the animated * value. * @param values A set of values that the animation will animate between over time. * @return An ObjectAnimator object that is set up to animate between the given values. */ public static ObjectAnimator ofObject(Object target, String propertyName, TypeEvaluator evaluator, Object... values) { ObjectAnimator anim = new ObjectAnimator(target, propertyName); anim.setObjectValues(values); anim.setEvaluator(evaluator); return anim; } /** * Constructs and returns an ObjectAnimator that animates between Object values. A single * value implies that that value is the one being animated to. Two values imply a starting * and ending values. More than two values imply a starting value, values to animate through * along the way, and an ending value (these values will be distributed evenly across * the duration of the animation). * * @param target The object whose property is to be animated. * @param property The property being animated. * @param evaluator A TypeEvaluator that will be called on each animation frame to * provide the necessary interpolation between the Object values to derive the animated * value. * @param values A set of values that the animation will animate between over time. * @return An ObjectAnimator object that is set up to animate between the given values. */ //public static <T, V> ObjectAnimator ofObject(T target, Property<T, V> property, // TypeEvaluator<V> evaluator, V... values) { // ObjectAnimator anim = new ObjectAnimator(target, property); // anim.setObjectValues(values); // anim.setEvaluator(evaluator); // return anim; //} /** * Constructs and returns an ObjectAnimator that animates between the sets of values specified * in <code>PropertyValueHolder</code> objects. This variant should be used when animating * several properties at once with the same ObjectAnimator, since PropertyValuesHolder allows * you to associate a set of animation values with a property name. * * @param target The object whose property is to be animated. Depending on how the * PropertyValuesObjects were constructed, the target object should either have the {@link * android.util.Property} objects used to construct the PropertyValuesHolder objects or (if the * PropertyValuesHOlder objects were created with property names) the target object should have * public methods on it called <code>setName()</code>, where <code>name</code> is the name of * the property passed in as the <code>propertyName</code> parameter for each of the * PropertyValuesHolder objects. * @param values A set of PropertyValuesHolder objects whose values will be animated between * over time. * @return An ObjectAnimator object that is set up to animate between the given values. */ public static ObjectAnimator ofPropertyValuesHolder(Object target, PropertyValuesHolder... values) { ObjectAnimator anim = new ObjectAnimator(); anim.mTarget = target; anim.setValues(values); return anim; } @Override public void setIntValues(int... values) { if (mValues == null || mValues.length == 0) { // No values yet - this animator is being constructed piecemeal. Init the values with // whatever the current propertyName is //if (mProperty != null) { // setValues(PropertyValuesHolder.ofInt(mProperty, values)); //} else { setValues(PropertyValuesHolder.ofInt(mPropertyName, values)); //} } else { super.setIntValues(values); } } @Override public void setFloatValues(float... values) { if (mValues == null || mValues.length == 0) { // No values yet - this animator is being constructed piecemeal. Init the values with // whatever the current propertyName is //if (mProperty != null) { // setValues(PropertyValuesHolder.ofFloat(mProperty, values)); //} else { setValues(PropertyValuesHolder.ofFloat(mPropertyName, values)); //} } else { super.setFloatValues(values); } } @Override public void setObjectValues(Object... values) { if (mValues == null || mValues.length == 0) { // No values yet - this animator is being constructed piecemeal. Init the values with // whatever the current propertyName is //if (mProperty != null) { // setValues(PropertyValuesHolder.ofObject(mProperty, (TypeEvaluator)null, values)); //} else { setValues(PropertyValuesHolder.ofObject(mPropertyName, (TypeEvaluator)null, values)); //} } else { super.setObjectValues(values); } } @Override public void start() { if (DBG) { Log.d("ObjectAnimator", "Anim target, duration: " + mTarget + ", " + getDuration()); for (int i = 0; i < mValues.length; ++i) { PropertyValuesHolder pvh = mValues[i]; ArrayList<Keyframe> keyframes = pvh.mKeyframeSet.mKeyframes; Log.d("ObjectAnimator", " Values[" + i + "]: " + pvh.getPropertyName() + ", " + keyframes.get(0).getValue() + ", " + keyframes.get(pvh.mKeyframeSet.mNumKeyframes - 1).getValue()); } } super.start(); } /** * This function is called immediately before processing the first animation * frame of an animation. If there is a nonzero <code>startDelay</code>, the * function is called after that delay ends. * It takes care of the final initialization steps for the * animation. This includes setting mEvaluator, if the user has not yet * set it up, and the setter/getter methods, if the user did not supply * them. * * <p>Overriders of this method should call the superclass method to cause * internal mechanisms to be set up correctly.</p> */ @Override void initAnimation() { if (!mInitialized) { // mValueType may change due to setter/getter setup; do this before calling super.init(), // which uses mValueType to set up the default type evaluator. int numValues = mValues.length; for (int i = 0; i < numValues; ++i) { mValues[i].setupSetterAndGetter(mTarget); } super.initAnimation(); } } /** * Sets the length of the animation. The default duration is 300 milliseconds. * * @param duration The length of the animation, in milliseconds. * @return ObjectAnimator The object called with setDuration(). This return * value makes it easier to compose statements together that construct and then set the * duration, as in * <code>ObjectAnimator.ofInt(target, propertyName, 0, 10).setDuration(500).start()</code>. */ @Override public ObjectAnimator setDuration(long duration) { super.setDuration(duration); return this; } /** * The target object whose property will be animated by this animation * * @return The object being animated */ public Object getTarget() { return mTarget; } /** * Sets the target object whose property will be animated by this animation * * @param target The object being animated */ @Override public void setTarget(Object target) { if (mTarget != target) { final Object oldTarget = mTarget; mTarget = target; if (oldTarget != null && target != null && oldTarget.getClass() == target.getClass()) { return; } // New target type should cause re-initialization prior to starting mInitialized = false; } } @Override public void setupStartValues() { initAnimation(); int numValues = mValues.length; for (int i = 0; i < numValues; ++i) { mValues[i].setupStartValue(mTarget); } } @Override public void setupEndValues() { initAnimation(); int numValues = mValues.length; for (int i = 0; i < numValues; ++i) { mValues[i].setupEndValue(mTarget); } } /** * This method is called with the elapsed fraction of the animation during every * animation frame. This function turns the elapsed fraction into an interpolated fraction * and then into an animated value (from the evaluator. The function is called mostly during * animation updates, but it is also called when the <code>end()</code> * function is called, to set the final value on the property. * * <p>Overrides of this method must call the superclass to perform the calculation * of the animated value.</p> * * @param fraction The elapsed fraction of the animation. */ @Override void animateValue(float fraction) { super.animateValue(fraction); int numValues = mValues.length; for (int i = 0; i < numValues; ++i) { mValues[i].setAnimatedValue(mTarget); } } @Override public ObjectAnimator clone() { final ObjectAnimator anim = (ObjectAnimator) super.clone(); return anim; } @Override public String toString() { String returnVal = "ObjectAnimator@" + Integer.toHexString(hashCode()) + ", target " + mTarget; if (mValues != null) { for (int i = 0; i < mValues.length; ++i) { returnVal += "\n " + mValues[i].toString(); } } return returnVal; } }
1162584980-google-io
libprojects/abs/src/com/actionbarsherlock/internal/nineoldandroids/animation/ObjectAnimator.java
Java
asf20
21,908
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.actionbarsherlock.internal.nineoldandroids.animation; import android.view.animation.Interpolator; /** * This class holds a time/value pair for an animation. The Keyframe class is used * by {@link ValueAnimator} to define the values that the animation target will have over the course * of the animation. As the time proceeds from one keyframe to the other, the value of the * target object will animate between the value at the previous keyframe and the value at the * next keyframe. Each keyframe also holds an optional {@link TimeInterpolator} * object, which defines the time interpolation over the intervalue preceding the keyframe. * * <p>The Keyframe class itself is abstract. The type-specific factory methods will return * a subclass of Keyframe specific to the type of value being stored. This is done to improve * performance when dealing with the most common cases (e.g., <code>float</code> and * <code>int</code> values). Other types will fall into a more general Keyframe class that * treats its values as Objects. Unless your animation requires dealing with a custom type * or a data structure that needs to be animated directly (and evaluated using an implementation * of {@link TypeEvaluator}), you should stick to using float and int as animations using those * types have lower runtime overhead than other types.</p> */ @SuppressWarnings("rawtypes") public abstract class Keyframe implements Cloneable { /** * The time at which mValue will hold true. */ float mFraction; /** * The type of the value in this Keyframe. This type is determined at construction time, * based on the type of the <code>value</code> object passed into the constructor. */ Class mValueType; /** * The optional time interpolator for the interval preceding this keyframe. A null interpolator * (the default) results in linear interpolation over the interval. */ private /*Time*/Interpolator mInterpolator = null; /** * Flag to indicate whether this keyframe has a valid value. This flag is used when an * animation first starts, to populate placeholder keyframes with real values derived * from the target object. */ boolean mHasValue = false; /** * Constructs a Keyframe object with the given time and value. The time defines the * time, as a proportion of an overall animation's duration, at which the value will hold true * for the animation. The value for the animation between keyframes will be calculated as * an interpolation between the values at those keyframes. * * @param fraction The time, expressed as a value between 0 and 1, representing the fraction * of time elapsed of the overall animation duration. * @param value The value that the object will animate to as the animation time approaches * the time in this keyframe, and the the value animated from as the time passes the time in * this keyframe. */ public static Keyframe ofInt(float fraction, int value) { return new IntKeyframe(fraction, value); } /** * Constructs a Keyframe object with the given time. The value at this time will be derived * from the target object when the animation first starts (note that this implies that keyframes * with no initial value must be used as part of an {@link ObjectAnimator}). * The time defines the * time, as a proportion of an overall animation's duration, at which the value will hold true * for the animation. The value for the animation between keyframes will be calculated as * an interpolation between the values at those keyframes. * * @param fraction The time, expressed as a value between 0 and 1, representing the fraction * of time elapsed of the overall animation duration. */ public static Keyframe ofInt(float fraction) { return new IntKeyframe(fraction); } /** * Constructs a Keyframe object with the given time and value. The time defines the * time, as a proportion of an overall animation's duration, at which the value will hold true * for the animation. The value for the animation between keyframes will be calculated as * an interpolation between the values at those keyframes. * * @param fraction The time, expressed as a value between 0 and 1, representing the fraction * of time elapsed of the overall animation duration. * @param value The value that the object will animate to as the animation time approaches * the time in this keyframe, and the the value animated from as the time passes the time in * this keyframe. */ public static Keyframe ofFloat(float fraction, float value) { return new FloatKeyframe(fraction, value); } /** * Constructs a Keyframe object with the given time. The value at this time will be derived * from the target object when the animation first starts (note that this implies that keyframes * with no initial value must be used as part of an {@link ObjectAnimator}). * The time defines the * time, as a proportion of an overall animation's duration, at which the value will hold true * for the animation. The value for the animation between keyframes will be calculated as * an interpolation between the values at those keyframes. * * @param fraction The time, expressed as a value between 0 and 1, representing the fraction * of time elapsed of the overall animation duration. */ public static Keyframe ofFloat(float fraction) { return new FloatKeyframe(fraction); } /** * Constructs a Keyframe object with the given time and value. The time defines the * time, as a proportion of an overall animation's duration, at which the value will hold true * for the animation. The value for the animation between keyframes will be calculated as * an interpolation between the values at those keyframes. * * @param fraction The time, expressed as a value between 0 and 1, representing the fraction * of time elapsed of the overall animation duration. * @param value The value that the object will animate to as the animation time approaches * the time in this keyframe, and the the value animated from as the time passes the time in * this keyframe. */ public static Keyframe ofObject(float fraction, Object value) { return new ObjectKeyframe(fraction, value); } /** * Constructs a Keyframe object with the given time. The value at this time will be derived * from the target object when the animation first starts (note that this implies that keyframes * with no initial value must be used as part of an {@link ObjectAnimator}). * The time defines the * time, as a proportion of an overall animation's duration, at which the value will hold true * for the animation. The value for the animation between keyframes will be calculated as * an interpolation between the values at those keyframes. * * @param fraction The time, expressed as a value between 0 and 1, representing the fraction * of time elapsed of the overall animation duration. */ public static Keyframe ofObject(float fraction) { return new ObjectKeyframe(fraction, null); } /** * Indicates whether this keyframe has a valid value. This method is called internally when * an {@link ObjectAnimator} first starts; keyframes without values are assigned values at * that time by deriving the value for the property from the target object. * * @return boolean Whether this object has a value assigned. */ public boolean hasValue() { return mHasValue; } /** * Gets the value for this Keyframe. * * @return The value for this Keyframe. */ public abstract Object getValue(); /** * Sets the value for this Keyframe. * * @param value value for this Keyframe. */ public abstract void setValue(Object value); /** * Gets the time for this keyframe, as a fraction of the overall animation duration. * * @return The time associated with this keyframe, as a fraction of the overall animation * duration. This should be a value between 0 and 1. */ public float getFraction() { return mFraction; } /** * Sets the time for this keyframe, as a fraction of the overall animation duration. * * @param fraction time associated with this keyframe, as a fraction of the overall animation * duration. This should be a value between 0 and 1. */ public void setFraction(float fraction) { mFraction = fraction; } /** * Gets the optional interpolator for this Keyframe. A value of <code>null</code> indicates * that there is no interpolation, which is the same as linear interpolation. * * @return The optional interpolator for this Keyframe. */ public /*Time*/Interpolator getInterpolator() { return mInterpolator; } /** * Sets the optional interpolator for this Keyframe. A value of <code>null</code> indicates * that there is no interpolation, which is the same as linear interpolation. * * @return The optional interpolator for this Keyframe. */ public void setInterpolator(/*Time*/Interpolator interpolator) { mInterpolator = interpolator; } /** * Gets the type of keyframe. This information is used by ValueAnimator to determine the type of * {@link TypeEvaluator} to use when calculating values between keyframes. The type is based * on the type of Keyframe created. * * @return The type of the value stored in the Keyframe. */ public Class getType() { return mValueType; } @Override public abstract Keyframe clone(); /** * This internal subclass is used for all types which are not int or float. */ static class ObjectKeyframe extends Keyframe { /** * The value of the animation at the time mFraction. */ Object mValue; ObjectKeyframe(float fraction, Object value) { mFraction = fraction; mValue = value; mHasValue = (value != null); mValueType = mHasValue ? value.getClass() : Object.class; } public Object getValue() { return mValue; } public void setValue(Object value) { mValue = value; mHasValue = (value != null); } @Override public ObjectKeyframe clone() { ObjectKeyframe kfClone = new ObjectKeyframe(getFraction(), mValue); kfClone.setInterpolator(getInterpolator()); return kfClone; } } /** * Internal subclass used when the keyframe value is of type int. */ static class IntKeyframe extends Keyframe { /** * The value of the animation at the time mFraction. */ int mValue; IntKeyframe(float fraction, int value) { mFraction = fraction; mValue = value; mValueType = int.class; mHasValue = true; } IntKeyframe(float fraction) { mFraction = fraction; mValueType = int.class; } public int getIntValue() { return mValue; } public Object getValue() { return mValue; } public void setValue(Object value) { if (value != null && value.getClass() == Integer.class) { mValue = ((Integer)value).intValue(); mHasValue = true; } } @Override public IntKeyframe clone() { IntKeyframe kfClone = new IntKeyframe(getFraction(), mValue); kfClone.setInterpolator(getInterpolator()); return kfClone; } } /** * Internal subclass used when the keyframe value is of type float. */ static class FloatKeyframe extends Keyframe { /** * The value of the animation at the time mFraction. */ float mValue; FloatKeyframe(float fraction, float value) { mFraction = fraction; mValue = value; mValueType = float.class; mHasValue = true; } FloatKeyframe(float fraction) { mFraction = fraction; mValueType = float.class; } public float getFloatValue() { return mValue; } public Object getValue() { return mValue; } public void setValue(Object value) { if (value != null && value.getClass() == Float.class) { mValue = ((Float)value).floatValue(); mHasValue = true; } } @Override public FloatKeyframe clone() { FloatKeyframe kfClone = new FloatKeyframe(getFraction(), mValue); kfClone.setInterpolator(getInterpolator()); return kfClone; } } }
1162584980-google-io
libprojects/abs/src/com/actionbarsherlock/internal/nineoldandroids/animation/Keyframe.java
Java
asf20
13,829
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.actionbarsherlock.internal.nineoldandroids.animation; import java.util.ArrayList; import android.view.animation.Interpolator; import com.actionbarsherlock.internal.nineoldandroids.animation.Keyframe.IntKeyframe; /** * This class holds a collection of IntKeyframe objects and is called by ValueAnimator to calculate * values between those keyframes for a given animation. The class internal to the animation * package because it is an implementation detail of how Keyframes are stored and used. * * <p>This type-specific subclass of KeyframeSet, along with the other type-specific subclass for * float, exists to speed up the getValue() method when there is no custom * TypeEvaluator set for the animation, so that values can be calculated without autoboxing to the * Object equivalents of these primitive types.</p> */ @SuppressWarnings("unchecked") class IntKeyframeSet extends KeyframeSet { private int firstValue; private int lastValue; private int deltaValue; private boolean firstTime = true; public IntKeyframeSet(IntKeyframe... keyframes) { super(keyframes); } @Override public Object getValue(float fraction) { return getIntValue(fraction); } @Override public IntKeyframeSet clone() { ArrayList<Keyframe> keyframes = mKeyframes; int numKeyframes = mKeyframes.size(); IntKeyframe[] newKeyframes = new IntKeyframe[numKeyframes]; for (int i = 0; i < numKeyframes; ++i) { newKeyframes[i] = (IntKeyframe) keyframes.get(i).clone(); } IntKeyframeSet newSet = new IntKeyframeSet(newKeyframes); return newSet; } public int getIntValue(float fraction) { if (mNumKeyframes == 2) { if (firstTime) { firstTime = false; firstValue = ((IntKeyframe) mKeyframes.get(0)).getIntValue(); lastValue = ((IntKeyframe) mKeyframes.get(1)).getIntValue(); deltaValue = lastValue - firstValue; } if (mInterpolator != null) { fraction = mInterpolator.getInterpolation(fraction); } if (mEvaluator == null) { return firstValue + (int)(fraction * deltaValue); } else { return ((Number)mEvaluator.evaluate(fraction, firstValue, lastValue)).intValue(); } } if (fraction <= 0f) { final IntKeyframe prevKeyframe = (IntKeyframe) mKeyframes.get(0); final IntKeyframe nextKeyframe = (IntKeyframe) mKeyframes.get(1); int prevValue = prevKeyframe.getIntValue(); int nextValue = nextKeyframe.getIntValue(); float prevFraction = prevKeyframe.getFraction(); float nextFraction = nextKeyframe.getFraction(); final /*Time*/Interpolator interpolator = nextKeyframe.getInterpolator(); if (interpolator != null) { fraction = interpolator.getInterpolation(fraction); } float intervalFraction = (fraction - prevFraction) / (nextFraction - prevFraction); return mEvaluator == null ? prevValue + (int)(intervalFraction * (nextValue - prevValue)) : ((Number)mEvaluator.evaluate(intervalFraction, prevValue, nextValue)). intValue(); } else if (fraction >= 1f) { final IntKeyframe prevKeyframe = (IntKeyframe) mKeyframes.get(mNumKeyframes - 2); final IntKeyframe nextKeyframe = (IntKeyframe) mKeyframes.get(mNumKeyframes - 1); int prevValue = prevKeyframe.getIntValue(); int nextValue = nextKeyframe.getIntValue(); float prevFraction = prevKeyframe.getFraction(); float nextFraction = nextKeyframe.getFraction(); final /*Time*/Interpolator interpolator = nextKeyframe.getInterpolator(); if (interpolator != null) { fraction = interpolator.getInterpolation(fraction); } float intervalFraction = (fraction - prevFraction) / (nextFraction - prevFraction); return mEvaluator == null ? prevValue + (int)(intervalFraction * (nextValue - prevValue)) : ((Number)mEvaluator.evaluate(intervalFraction, prevValue, nextValue)).intValue(); } IntKeyframe prevKeyframe = (IntKeyframe) mKeyframes.get(0); for (int i = 1; i < mNumKeyframes; ++i) { IntKeyframe nextKeyframe = (IntKeyframe) mKeyframes.get(i); if (fraction < nextKeyframe.getFraction()) { final /*Time*/Interpolator interpolator = nextKeyframe.getInterpolator(); if (interpolator != null) { fraction = interpolator.getInterpolation(fraction); } float intervalFraction = (fraction - prevKeyframe.getFraction()) / (nextKeyframe.getFraction() - prevKeyframe.getFraction()); int prevValue = prevKeyframe.getIntValue(); int nextValue = nextKeyframe.getIntValue(); return mEvaluator == null ? prevValue + (int)(intervalFraction * (nextValue - prevValue)) : ((Number)mEvaluator.evaluate(intervalFraction, prevValue, nextValue)). intValue(); } prevKeyframe = nextKeyframe; } // shouldn't get here return ((Number)mKeyframes.get(mNumKeyframes - 1).getValue()).intValue(); } }
1162584980-google-io
libprojects/abs/src/com/actionbarsherlock/internal/nineoldandroids/animation/IntKeyframeSet.java
Java
asf20
6,217
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.actionbarsherlock.internal.nineoldandroids.animation; /** * This evaluator can be used to perform type interpolation between <code>float</code> values. */ public class FloatEvaluator implements TypeEvaluator<Number> { /** * This function returns the result of linearly interpolating the start and end values, with * <code>fraction</code> representing the proportion between the start and end values. The * calculation is a simple parametric calculation: <code>result = x0 + t * (v1 - v0)</code>, * where <code>x0</code> is <code>startValue</code>, <code>x1</code> is <code>endValue</code>, * and <code>t</code> is <code>fraction</code>. * * @param fraction The fraction from the starting to the ending values * @param startValue The start value; should be of type <code>float</code> or * <code>Float</code> * @param endValue The end value; should be of type <code>float</code> or <code>Float</code> * @return A linear interpolation between the start and end values, given the * <code>fraction</code> parameter. */ public Float evaluate(float fraction, Number startValue, Number endValue) { float startFloat = startValue.floatValue(); return startFloat + fraction * (endValue.floatValue() - startFloat); } }
1162584980-google-io
libprojects/abs/src/com/actionbarsherlock/internal/nineoldandroids/animation/FloatEvaluator.java
Java
asf20
1,966
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.actionbarsherlock.internal.nineoldandroids.animation; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import android.view.animation.Interpolator; /** * This class plays a set of {@link Animator} objects in the specified order. Animations * can be set up to play together, in sequence, or after a specified delay. * * <p>There are two different approaches to adding animations to a <code>AnimatorSet</code>: * either the {@link AnimatorSet#playTogether(Animator[]) playTogether()} or * {@link AnimatorSet#playSequentially(Animator[]) playSequentially()} methods can be called to add * a set of animations all at once, or the {@link AnimatorSet#play(Animator)} can be * used in conjunction with methods in the {@link AnimatorSet.Builder Builder} * class to add animations * one by one.</p> * * <p>It is possible to set up a <code>AnimatorSet</code> with circular dependencies between * its animations. For example, an animation a1 could be set up to start before animation a2, a2 * before a3, and a3 before a1. The results of this configuration are undefined, but will typically * result in none of the affected animations being played. Because of this (and because * circular dependencies do not make logical sense anyway), circular dependencies * should be avoided, and the dependency flow of animations should only be in one direction. */ @SuppressWarnings("unchecked") public final class AnimatorSet extends Animator { /** * Internal variables * NOTE: This object implements the clone() method, making a deep copy of any referenced * objects. As other non-trivial fields are added to this class, make sure to add logic * to clone() to make deep copies of them. */ /** * Tracks animations currently being played, so that we know what to * cancel or end when cancel() or end() is called on this AnimatorSet */ private ArrayList<Animator> mPlayingSet = new ArrayList<Animator>(); /** * Contains all nodes, mapped to their respective Animators. When new * dependency information is added for an Animator, we want to add it * to a single node representing that Animator, not create a new Node * if one already exists. */ private HashMap<Animator, Node> mNodeMap = new HashMap<Animator, Node>(); /** * Set of all nodes created for this AnimatorSet. This list is used upon * starting the set, and the nodes are placed in sorted order into the * sortedNodes collection. */ private ArrayList<Node> mNodes = new ArrayList<Node>(); /** * The sorted list of nodes. This is the order in which the animations will * be played. The details about when exactly they will be played depend * on the dependency relationships of the nodes. */ private ArrayList<Node> mSortedNodes = new ArrayList<Node>(); /** * Flag indicating whether the nodes should be sorted prior to playing. This * flag allows us to cache the previous sorted nodes so that if the sequence * is replayed with no changes, it does not have to re-sort the nodes again. */ private boolean mNeedsSort = true; private AnimatorSetListener mSetListener = null; /** * Flag indicating that the AnimatorSet has been manually * terminated (by calling cancel() or end()). * This flag is used to avoid starting other animations when currently-playing * child animations of this AnimatorSet end. It also determines whether cancel/end * notifications are sent out via the normal AnimatorSetListener mechanism. */ boolean mTerminated = false; /** * Indicates whether an AnimatorSet has been start()'d, whether or * not there is a nonzero startDelay. */ private boolean mStarted = false; // The amount of time in ms to delay starting the animation after start() is called private long mStartDelay = 0; // Animator used for a nonzero startDelay private ValueAnimator mDelayAnim = null; // How long the child animations should last in ms. The default value is negative, which // simply means that there is no duration set on the AnimatorSet. When a real duration is // set, it is passed along to the child animations. private long mDuration = -1; /** * Sets up this AnimatorSet to play all of the supplied animations at the same time. * * @param items The animations that will be started simultaneously. */ public void playTogether(Animator... items) { if (items != null) { mNeedsSort = true; Builder builder = play(items[0]); for (int i = 1; i < items.length; ++i) { builder.with(items[i]); } } } /** * Sets up this AnimatorSet to play all of the supplied animations at the same time. * * @param items The animations that will be started simultaneously. */ public void playTogether(Collection<Animator> items) { if (items != null && items.size() > 0) { mNeedsSort = true; Builder builder = null; for (Animator anim : items) { if (builder == null) { builder = play(anim); } else { builder.with(anim); } } } } /** * Sets up this AnimatorSet to play each of the supplied animations when the * previous animation ends. * * @param items The animations that will be started one after another. */ public void playSequentially(Animator... items) { if (items != null) { mNeedsSort = true; if (items.length == 1) { play(items[0]); } else { for (int i = 0; i < items.length - 1; ++i) { play(items[i]).before(items[i+1]); } } } } /** * Sets up this AnimatorSet to play each of the supplied animations when the * previous animation ends. * * @param items The animations that will be started one after another. */ public void playSequentially(List<Animator> items) { if (items != null && items.size() > 0) { mNeedsSort = true; if (items.size() == 1) { play(items.get(0)); } else { for (int i = 0; i < items.size() - 1; ++i) { play(items.get(i)).before(items.get(i+1)); } } } } /** * Returns the current list of child Animator objects controlled by this * AnimatorSet. This is a copy of the internal list; modifications to the returned list * will not affect the AnimatorSet, although changes to the underlying Animator objects * will affect those objects being managed by the AnimatorSet. * * @return ArrayList<Animator> The list of child animations of this AnimatorSet. */ public ArrayList<Animator> getChildAnimations() { ArrayList<Animator> childList = new ArrayList<Animator>(); for (Node node : mNodes) { childList.add(node.animation); } return childList; } /** * Sets the target object for all current {@link #getChildAnimations() child animations} * of this AnimatorSet that take targets ({@link ObjectAnimator} and * AnimatorSet). * * @param target The object being animated */ @Override public void setTarget(Object target) { for (Node node : mNodes) { Animator animation = node.animation; if (animation instanceof AnimatorSet) { ((AnimatorSet)animation).setTarget(target); } else if (animation instanceof ObjectAnimator) { ((ObjectAnimator)animation).setTarget(target); } } } /** * Sets the TimeInterpolator for all current {@link #getChildAnimations() child animations} * of this AnimatorSet. * * @param interpolator the interpolator to be used by each child animation of this AnimatorSet */ @Override public void setInterpolator(/*Time*/Interpolator interpolator) { for (Node node : mNodes) { node.animation.setInterpolator(interpolator); } } /** * This method creates a <code>Builder</code> object, which is used to * set up playing constraints. This initial <code>play()</code> method * tells the <code>Builder</code> the animation that is the dependency for * the succeeding commands to the <code>Builder</code>. For example, * calling <code>play(a1).with(a2)</code> sets up the AnimatorSet to play * <code>a1</code> and <code>a2</code> at the same time, * <code>play(a1).before(a2)</code> sets up the AnimatorSet to play * <code>a1</code> first, followed by <code>a2</code>, and * <code>play(a1).after(a2)</code> sets up the AnimatorSet to play * <code>a2</code> first, followed by <code>a1</code>. * * <p>Note that <code>play()</code> is the only way to tell the * <code>Builder</code> the animation upon which the dependency is created, * so successive calls to the various functions in <code>Builder</code> * will all refer to the initial parameter supplied in <code>play()</code> * as the dependency of the other animations. For example, calling * <code>play(a1).before(a2).before(a3)</code> will play both <code>a2</code> * and <code>a3</code> when a1 ends; it does not set up a dependency between * <code>a2</code> and <code>a3</code>.</p> * * @param anim The animation that is the dependency used in later calls to the * methods in the returned <code>Builder</code> object. A null parameter will result * in a null <code>Builder</code> return value. * @return Builder The object that constructs the AnimatorSet based on the dependencies * outlined in the calls to <code>play</code> and the other methods in the * <code>Builder</code object. */ public Builder play(Animator anim) { if (anim != null) { mNeedsSort = true; return new Builder(anim); } return null; } /** * {@inheritDoc} * * <p>Note that canceling a <code>AnimatorSet</code> also cancels all of the animations that it * is responsible for.</p> */ @Override public void cancel() { mTerminated = true; if (isStarted()) { ArrayList<AnimatorListener> tmpListeners = null; if (mListeners != null) { tmpListeners = (ArrayList<AnimatorListener>) mListeners.clone(); for (AnimatorListener listener : tmpListeners) { listener.onAnimationCancel(this); } } if (mDelayAnim != null && mDelayAnim.isRunning()) { // If we're currently in the startDelay period, just cancel that animator and // send out the end event to all listeners mDelayAnim.cancel(); } else if (mSortedNodes.size() > 0) { for (Node node : mSortedNodes) { node.animation.cancel(); } } if (tmpListeners != null) { for (AnimatorListener listener : tmpListeners) { listener.onAnimationEnd(this); } } mStarted = false; } } /** * {@inheritDoc} * * <p>Note that ending a <code>AnimatorSet</code> also ends all of the animations that it is * responsible for.</p> */ @Override public void end() { mTerminated = true; if (isStarted()) { if (mSortedNodes.size() != mNodes.size()) { // hasn't been started yet - sort the nodes now, then end them sortNodes(); for (Node node : mSortedNodes) { if (mSetListener == null) { mSetListener = new AnimatorSetListener(this); } node.animation.addListener(mSetListener); } } if (mDelayAnim != null) { mDelayAnim.cancel(); } if (mSortedNodes.size() > 0) { for (Node node : mSortedNodes) { node.animation.end(); } } if (mListeners != null) { ArrayList<AnimatorListener> tmpListeners = (ArrayList<AnimatorListener>) mListeners.clone(); for (AnimatorListener listener : tmpListeners) { listener.onAnimationEnd(this); } } mStarted = false; } } /** * Returns true if any of the child animations of this AnimatorSet have been started and have * not yet ended. * @return Whether this AnimatorSet has been started and has not yet ended. */ @Override public boolean isRunning() { for (Node node : mNodes) { if (node.animation.isRunning()) { return true; } } return false; } @Override public boolean isStarted() { return mStarted; } /** * The amount of time, in milliseconds, to delay starting the animation after * {@link #start()} is called. * * @return the number of milliseconds to delay running the animation */ @Override public long getStartDelay() { return mStartDelay; } /** * The amount of time, in milliseconds, to delay starting the animation after * {@link #start()} is called. * @param startDelay The amount of the delay, in milliseconds */ @Override public void setStartDelay(long startDelay) { mStartDelay = startDelay; } /** * Gets the length of each of the child animations of this AnimatorSet. This value may * be less than 0, which indicates that no duration has been set on this AnimatorSet * and each of the child animations will use their own duration. * * @return The length of the animation, in milliseconds, of each of the child * animations of this AnimatorSet. */ @Override public long getDuration() { return mDuration; } /** * Sets the length of each of the current child animations of this AnimatorSet. By default, * each child animation will use its own duration. If the duration is set on the AnimatorSet, * then each child animation inherits this duration. * * @param duration The length of the animation, in milliseconds, of each of the child * animations of this AnimatorSet. */ @Override public AnimatorSet setDuration(long duration) { if (duration < 0) { throw new IllegalArgumentException("duration must be a value of zero or greater"); } for (Node node : mNodes) { // TODO: don't set the duration of the timing-only nodes created by AnimatorSet to // insert "play-after" delays node.animation.setDuration(duration); } mDuration = duration; return this; } @Override public void setupStartValues() { for (Node node : mNodes) { node.animation.setupStartValues(); } } @Override public void setupEndValues() { for (Node node : mNodes) { node.animation.setupEndValues(); } } /** * {@inheritDoc} * * <p>Starting this <code>AnimatorSet</code> will, in turn, start the animations for which * it is responsible. The details of when exactly those animations are started depends on * the dependency relationships that have been set up between the animations. */ @Override public void start() { mTerminated = false; mStarted = true; // First, sort the nodes (if necessary). This will ensure that sortedNodes // contains the animation nodes in the correct order. sortNodes(); int numSortedNodes = mSortedNodes.size(); for (int i = 0; i < numSortedNodes; ++i) { Node node = mSortedNodes.get(i); // First, clear out the old listeners ArrayList<AnimatorListener> oldListeners = node.animation.getListeners(); if (oldListeners != null && oldListeners.size() > 0) { final ArrayList<AnimatorListener> clonedListeners = new ArrayList<AnimatorListener>(oldListeners); for (AnimatorListener listener : clonedListeners) { if (listener instanceof DependencyListener || listener instanceof AnimatorSetListener) { node.animation.removeListener(listener); } } } } // nodesToStart holds the list of nodes to be started immediately. We don't want to // start the animations in the loop directly because we first need to set up // dependencies on all of the nodes. For example, we don't want to start an animation // when some other animation also wants to start when the first animation begins. final ArrayList<Node> nodesToStart = new ArrayList<Node>(); for (int i = 0; i < numSortedNodes; ++i) { Node node = mSortedNodes.get(i); if (mSetListener == null) { mSetListener = new AnimatorSetListener(this); } if (node.dependencies == null || node.dependencies.size() == 0) { nodesToStart.add(node); } else { int numDependencies = node.dependencies.size(); for (int j = 0; j < numDependencies; ++j) { Dependency dependency = node.dependencies.get(j); dependency.node.animation.addListener( new DependencyListener(this, node, dependency.rule)); } node.tmpDependencies = (ArrayList<Dependency>) node.dependencies.clone(); } node.animation.addListener(mSetListener); } // Now that all dependencies are set up, start the animations that should be started. if (mStartDelay <= 0) { for (Node node : nodesToStart) { node.animation.start(); mPlayingSet.add(node.animation); } } else { mDelayAnim = ValueAnimator.ofFloat(0f, 1f); mDelayAnim.setDuration(mStartDelay); mDelayAnim.addListener(new AnimatorListenerAdapter() { boolean canceled = false; public void onAnimationCancel(Animator anim) { canceled = true; } public void onAnimationEnd(Animator anim) { if (!canceled) { int numNodes = nodesToStart.size(); for (int i = 0; i < numNodes; ++i) { Node node = nodesToStart.get(i); node.animation.start(); mPlayingSet.add(node.animation); } } } }); mDelayAnim.start(); } if (mListeners != null) { ArrayList<AnimatorListener> tmpListeners = (ArrayList<AnimatorListener>) mListeners.clone(); int numListeners = tmpListeners.size(); for (int i = 0; i < numListeners; ++i) { tmpListeners.get(i).onAnimationStart(this); } } if (mNodes.size() == 0 && mStartDelay == 0) { // Handle unusual case where empty AnimatorSet is started - should send out // end event immediately since the event will not be sent out at all otherwise mStarted = false; if (mListeners != null) { ArrayList<AnimatorListener> tmpListeners = (ArrayList<AnimatorListener>) mListeners.clone(); int numListeners = tmpListeners.size(); for (int i = 0; i < numListeners; ++i) { tmpListeners.get(i).onAnimationEnd(this); } } } } @Override public AnimatorSet clone() { final AnimatorSet anim = (AnimatorSet) super.clone(); /* * The basic clone() operation copies all items. This doesn't work very well for * AnimatorSet, because it will copy references that need to be recreated and state * that may not apply. What we need to do now is put the clone in an uninitialized * state, with fresh, empty data structures. Then we will build up the nodes list * manually, as we clone each Node (and its animation). The clone will then be sorted, * and will populate any appropriate lists, when it is started. */ anim.mNeedsSort = true; anim.mTerminated = false; anim.mStarted = false; anim.mPlayingSet = new ArrayList<Animator>(); anim.mNodeMap = new HashMap<Animator, Node>(); anim.mNodes = new ArrayList<Node>(); anim.mSortedNodes = new ArrayList<Node>(); // Walk through the old nodes list, cloning each node and adding it to the new nodemap. // One problem is that the old node dependencies point to nodes in the old AnimatorSet. // We need to track the old/new nodes in order to reconstruct the dependencies in the clone. HashMap<Node, Node> nodeCloneMap = new HashMap<Node, Node>(); // <old, new> for (Node node : mNodes) { Node nodeClone = node.clone(); nodeCloneMap.put(node, nodeClone); anim.mNodes.add(nodeClone); anim.mNodeMap.put(nodeClone.animation, nodeClone); // Clear out the dependencies in the clone; we'll set these up manually later nodeClone.dependencies = null; nodeClone.tmpDependencies = null; nodeClone.nodeDependents = null; nodeClone.nodeDependencies = null; // clear out any listeners that were set up by the AnimatorSet; these will // be set up when the clone's nodes are sorted ArrayList<AnimatorListener> cloneListeners = nodeClone.animation.getListeners(); if (cloneListeners != null) { ArrayList<AnimatorListener> listenersToRemove = null; for (AnimatorListener listener : cloneListeners) { if (listener instanceof AnimatorSetListener) { if (listenersToRemove == null) { listenersToRemove = new ArrayList<AnimatorListener>(); } listenersToRemove.add(listener); } } if (listenersToRemove != null) { for (AnimatorListener listener : listenersToRemove) { cloneListeners.remove(listener); } } } } // Now that we've cloned all of the nodes, we're ready to walk through their // dependencies, mapping the old dependencies to the new nodes for (Node node : mNodes) { Node nodeClone = nodeCloneMap.get(node); if (node.dependencies != null) { for (Dependency dependency : node.dependencies) { Node clonedDependencyNode = nodeCloneMap.get(dependency.node); Dependency cloneDependency = new Dependency(clonedDependencyNode, dependency.rule); nodeClone.addDependency(cloneDependency); } } } return anim; } /** * This class is the mechanism by which animations are started based on events in other * animations. If an animation has multiple dependencies on other animations, then * all dependencies must be satisfied before the animation is started. */ private static class DependencyListener implements AnimatorListener { private AnimatorSet mAnimatorSet; // The node upon which the dependency is based. private Node mNode; // The Dependency rule (WITH or AFTER) that the listener should wait for on // the node private int mRule; public DependencyListener(AnimatorSet animatorSet, Node node, int rule) { this.mAnimatorSet = animatorSet; this.mNode = node; this.mRule = rule; } /** * Ignore cancel events for now. We may want to handle this eventually, * to prevent follow-on animations from running when some dependency * animation is canceled. */ public void onAnimationCancel(Animator animation) { } /** * An end event is received - see if this is an event we are listening for */ public void onAnimationEnd(Animator animation) { if (mRule == Dependency.AFTER) { startIfReady(animation); } } /** * Ignore repeat events for now */ public void onAnimationRepeat(Animator animation) { } /** * A start event is received - see if this is an event we are listening for */ public void onAnimationStart(Animator animation) { if (mRule == Dependency.WITH) { startIfReady(animation); } } /** * Check whether the event received is one that the node was waiting for. * If so, mark it as complete and see whether it's time to start * the animation. * @param dependencyAnimation the animation that sent the event. */ private void startIfReady(Animator dependencyAnimation) { if (mAnimatorSet.mTerminated) { // if the parent AnimatorSet was canceled, then don't start any dependent anims return; } Dependency dependencyToRemove = null; int numDependencies = mNode.tmpDependencies.size(); for (int i = 0; i < numDependencies; ++i) { Dependency dependency = mNode.tmpDependencies.get(i); if (dependency.rule == mRule && dependency.node.animation == dependencyAnimation) { // rule fired - remove the dependency and listener and check to // see whether it's time to start the animation dependencyToRemove = dependency; dependencyAnimation.removeListener(this); break; } } mNode.tmpDependencies.remove(dependencyToRemove); if (mNode.tmpDependencies.size() == 0) { // all dependencies satisfied: start the animation mNode.animation.start(); mAnimatorSet.mPlayingSet.add(mNode.animation); } } } private class AnimatorSetListener implements AnimatorListener { private AnimatorSet mAnimatorSet; AnimatorSetListener(AnimatorSet animatorSet) { mAnimatorSet = animatorSet; } public void onAnimationCancel(Animator animation) { if (!mTerminated) { // Listeners are already notified of the AnimatorSet canceling in cancel(). // The logic below only kicks in when animations end normally if (mPlayingSet.size() == 0) { if (mListeners != null) { int numListeners = mListeners.size(); for (int i = 0; i < numListeners; ++i) { mListeners.get(i).onAnimationCancel(mAnimatorSet); } } } } } public void onAnimationEnd(Animator animation) { animation.removeListener(this); mPlayingSet.remove(animation); Node animNode = mAnimatorSet.mNodeMap.get(animation); animNode.done = true; if (!mTerminated) { // Listeners are already notified of the AnimatorSet ending in cancel() or // end(); the logic below only kicks in when animations end normally ArrayList<Node> sortedNodes = mAnimatorSet.mSortedNodes; boolean allDone = true; int numSortedNodes = sortedNodes.size(); for (int i = 0; i < numSortedNodes; ++i) { if (!sortedNodes.get(i).done) { allDone = false; break; } } if (allDone) { // If this was the last child animation to end, then notify listeners that this // AnimatorSet has ended if (mListeners != null) { ArrayList<AnimatorListener> tmpListeners = (ArrayList<AnimatorListener>) mListeners.clone(); int numListeners = tmpListeners.size(); for (int i = 0; i < numListeners; ++i) { tmpListeners.get(i).onAnimationEnd(mAnimatorSet); } } mAnimatorSet.mStarted = false; } } } // Nothing to do public void onAnimationRepeat(Animator animation) { } // Nothing to do public void onAnimationStart(Animator animation) { } } /** * This method sorts the current set of nodes, if needed. The sort is a simple * DependencyGraph sort, which goes like this: * - All nodes without dependencies become 'roots' * - while roots list is not null * - for each root r * - add r to sorted list * - remove r as a dependency from any other node * - any nodes with no dependencies are added to the roots list */ private void sortNodes() { if (mNeedsSort) { mSortedNodes.clear(); ArrayList<Node> roots = new ArrayList<Node>(); int numNodes = mNodes.size(); for (int i = 0; i < numNodes; ++i) { Node node = mNodes.get(i); if (node.dependencies == null || node.dependencies.size() == 0) { roots.add(node); } } ArrayList<Node> tmpRoots = new ArrayList<Node>(); while (roots.size() > 0) { int numRoots = roots.size(); for (int i = 0; i < numRoots; ++i) { Node root = roots.get(i); mSortedNodes.add(root); if (root.nodeDependents != null) { int numDependents = root.nodeDependents.size(); for (int j = 0; j < numDependents; ++j) { Node node = root.nodeDependents.get(j); node.nodeDependencies.remove(root); if (node.nodeDependencies.size() == 0) { tmpRoots.add(node); } } } } roots.clear(); roots.addAll(tmpRoots); tmpRoots.clear(); } mNeedsSort = false; if (mSortedNodes.size() != mNodes.size()) { throw new IllegalStateException("Circular dependencies cannot exist" + " in AnimatorSet"); } } else { // Doesn't need sorting, but still need to add in the nodeDependencies list // because these get removed as the event listeners fire and the dependencies // are satisfied int numNodes = mNodes.size(); for (int i = 0; i < numNodes; ++i) { Node node = mNodes.get(i); if (node.dependencies != null && node.dependencies.size() > 0) { int numDependencies = node.dependencies.size(); for (int j = 0; j < numDependencies; ++j) { Dependency dependency = node.dependencies.get(j); if (node.nodeDependencies == null) { node.nodeDependencies = new ArrayList<Node>(); } if (!node.nodeDependencies.contains(dependency.node)) { node.nodeDependencies.add(dependency.node); } } } // nodes are 'done' by default; they become un-done when started, and done // again when ended node.done = false; } } } /** * Dependency holds information about the node that some other node is * dependent upon and the nature of that dependency. * */ private static class Dependency { static final int WITH = 0; // dependent node must start with this dependency node static final int AFTER = 1; // dependent node must start when this dependency node finishes // The node that the other node with this Dependency is dependent upon public Node node; // The nature of the dependency (WITH or AFTER) public int rule; public Dependency(Node node, int rule) { this.node = node; this.rule = rule; } } /** * A Node is an embodiment of both the Animator that it wraps as well as * any dependencies that are associated with that Animation. This includes * both dependencies upon other nodes (in the dependencies list) as * well as dependencies of other nodes upon this (in the nodeDependents list). */ private static class Node implements Cloneable { public Animator animation; /** * These are the dependencies that this node's animation has on other * nodes. For example, if this node's animation should begin with some * other animation ends, then there will be an item in this node's * dependencies list for that other animation's node. */ public ArrayList<Dependency> dependencies = null; /** * tmpDependencies is a runtime detail. We use the dependencies list for sorting. * But we also use the list to keep track of when multiple dependencies are satisfied, * but removing each dependency as it is satisfied. We do not want to remove * the dependency itself from the list, because we need to retain that information * if the AnimatorSet is launched in the future. So we create a copy of the dependency * list when the AnimatorSet starts and use this tmpDependencies list to track the * list of satisfied dependencies. */ public ArrayList<Dependency> tmpDependencies = null; /** * nodeDependencies is just a list of the nodes that this Node is dependent upon. * This information is used in sortNodes(), to determine when a node is a root. */ public ArrayList<Node> nodeDependencies = null; /** * nodeDepdendents is the list of nodes that have this node as a dependency. This * is a utility field used in sortNodes to facilitate removing this node as a * dependency when it is a root node. */ public ArrayList<Node> nodeDependents = null; /** * Flag indicating whether the animation in this node is finished. This flag * is used by AnimatorSet to check, as each animation ends, whether all child animations * are done and it's time to send out an end event for the entire AnimatorSet. */ public boolean done = false; /** * Constructs the Node with the animation that it encapsulates. A Node has no * dependencies by default; dependencies are added via the addDependency() * method. * * @param animation The animation that the Node encapsulates. */ public Node(Animator animation) { this.animation = animation; } /** * Add a dependency to this Node. The dependency includes information about the * node that this node is dependency upon and the nature of the dependency. * @param dependency */ public void addDependency(Dependency dependency) { if (dependencies == null) { dependencies = new ArrayList<Dependency>(); nodeDependencies = new ArrayList<Node>(); } dependencies.add(dependency); if (!nodeDependencies.contains(dependency.node)) { nodeDependencies.add(dependency.node); } Node dependencyNode = dependency.node; if (dependencyNode.nodeDependents == null) { dependencyNode.nodeDependents = new ArrayList<Node>(); } dependencyNode.nodeDependents.add(this); } @Override public Node clone() { try { Node node = (Node) super.clone(); node.animation = animation.clone(); return node; } catch (CloneNotSupportedException e) { throw new AssertionError(); } } } /** * The <code>Builder</code> object is a utility class to facilitate adding animations to a * <code>AnimatorSet</code> along with the relationships between the various animations. The * intention of the <code>Builder</code> methods, along with the {@link * AnimatorSet#play(Animator) play()} method of <code>AnimatorSet</code> is to make it possible * to express the dependency relationships of animations in a natural way. Developers can also * use the {@link AnimatorSet#playTogether(Animator[]) playTogether()} and {@link * AnimatorSet#playSequentially(Animator[]) playSequentially()} methods if these suit the need, * but it might be easier in some situations to express the AnimatorSet of animations in pairs. * <p/> * <p>The <code>Builder</code> object cannot be constructed directly, but is rather constructed * internally via a call to {@link AnimatorSet#play(Animator)}.</p> * <p/> * <p>For example, this sets up a AnimatorSet to play anim1 and anim2 at the same time, anim3 to * play when anim2 finishes, and anim4 to play when anim3 finishes:</p> * <pre> * AnimatorSet s = new AnimatorSet(); * s.play(anim1).with(anim2); * s.play(anim2).before(anim3); * s.play(anim4).after(anim3); * </pre> * <p/> * <p>Note in the example that both {@link Builder#before(Animator)} and {@link * Builder#after(Animator)} are used. These are just different ways of expressing the same * relationship and are provided to make it easier to say things in a way that is more natural, * depending on the situation.</p> * <p/> * <p>It is possible to make several calls into the same <code>Builder</code> object to express * multiple relationships. However, note that it is only the animation passed into the initial * {@link AnimatorSet#play(Animator)} method that is the dependency in any of the successive * calls to the <code>Builder</code> object. For example, the following code starts both anim2 * and anim3 when anim1 ends; there is no direct dependency relationship between anim2 and * anim3: * <pre> * AnimatorSet s = new AnimatorSet(); * s.play(anim1).before(anim2).before(anim3); * </pre> * If the desired result is to play anim1 then anim2 then anim3, this code expresses the * relationship correctly:</p> * <pre> * AnimatorSet s = new AnimatorSet(); * s.play(anim1).before(anim2); * s.play(anim2).before(anim3); * </pre> * <p/> * <p>Note that it is possible to express relationships that cannot be resolved and will not * result in sensible results. For example, <code>play(anim1).after(anim1)</code> makes no * sense. In general, circular dependencies like this one (or more indirect ones where a depends * on b, which depends on c, which depends on a) should be avoided. Only create AnimatorSets * that can boil down to a simple, one-way relationship of animations starting with, before, and * after other, different, animations.</p> */ public class Builder { /** * This tracks the current node being processed. It is supplied to the play() method * of AnimatorSet and passed into the constructor of Builder. */ private Node mCurrentNode; /** * package-private constructor. Builders are only constructed by AnimatorSet, when the * play() method is called. * * @param anim The animation that is the dependency for the other animations passed into * the other methods of this Builder object. */ Builder(Animator anim) { mCurrentNode = mNodeMap.get(anim); if (mCurrentNode == null) { mCurrentNode = new Node(anim); mNodeMap.put(anim, mCurrentNode); mNodes.add(mCurrentNode); } } /** * Sets up the given animation to play at the same time as the animation supplied in the * {@link AnimatorSet#play(Animator)} call that created this <code>Builder</code> object. * * @param anim The animation that will play when the animation supplied to the * {@link AnimatorSet#play(Animator)} method starts. */ public Builder with(Animator anim) { Node node = mNodeMap.get(anim); if (node == null) { node = new Node(anim); mNodeMap.put(anim, node); mNodes.add(node); } Dependency dependency = new Dependency(mCurrentNode, Dependency.WITH); node.addDependency(dependency); return this; } /** * Sets up the given animation to play when the animation supplied in the * {@link AnimatorSet#play(Animator)} call that created this <code>Builder</code> object * ends. * * @param anim The animation that will play when the animation supplied to the * {@link AnimatorSet#play(Animator)} method ends. */ public Builder before(Animator anim) { Node node = mNodeMap.get(anim); if (node == null) { node = new Node(anim); mNodeMap.put(anim, node); mNodes.add(node); } Dependency dependency = new Dependency(mCurrentNode, Dependency.AFTER); node.addDependency(dependency); return this; } /** * Sets up the given animation to play when the animation supplied in the * {@link AnimatorSet#play(Animator)} call that created this <code>Builder</code> object * to start when the animation supplied in this method call ends. * * @param anim The animation whose end will cause the animation supplied to the * {@link AnimatorSet#play(Animator)} method to play. */ public Builder after(Animator anim) { Node node = mNodeMap.get(anim); if (node == null) { node = new Node(anim); mNodeMap.put(anim, node); mNodes.add(node); } Dependency dependency = new Dependency(node, Dependency.AFTER); mCurrentNode.addDependency(dependency); return this; } /** * Sets up the animation supplied in the * {@link AnimatorSet#play(Animator)} call that created this <code>Builder</code> object * to play when the given amount of time elapses. * * @param delay The number of milliseconds that should elapse before the * animation starts. */ public Builder after(long delay) { // setup dummy ValueAnimator just to run the clock ValueAnimator anim = ValueAnimator.ofFloat(0f, 1f); anim.setDuration(delay); after(anim); return this; } } }
1162584980-google-io
libprojects/abs/src/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorSet.java
Java
asf20
45,590
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.actionbarsherlock.internal.nineoldandroids.animation; import java.util.ArrayList; import java.util.Arrays; import android.view.animation.Interpolator; import com.actionbarsherlock.internal.nineoldandroids.animation.Keyframe.FloatKeyframe; import com.actionbarsherlock.internal.nineoldandroids.animation.Keyframe.IntKeyframe; import com.actionbarsherlock.internal.nineoldandroids.animation.Keyframe.ObjectKeyframe; /** * This class holds a collection of Keyframe objects and is called by ValueAnimator to calculate * values between those keyframes for a given animation. The class internal to the animation * package because it is an implementation detail of how Keyframes are stored and used. */ @SuppressWarnings({"rawtypes", "unchecked"}) class KeyframeSet { int mNumKeyframes; Keyframe mFirstKeyframe; Keyframe mLastKeyframe; /*Time*/Interpolator mInterpolator; // only used in the 2-keyframe case ArrayList<Keyframe> mKeyframes; // only used when there are not 2 keyframes TypeEvaluator mEvaluator; public KeyframeSet(Keyframe... keyframes) { mNumKeyframes = keyframes.length; mKeyframes = new ArrayList<Keyframe>(); mKeyframes.addAll(Arrays.asList(keyframes)); mFirstKeyframe = mKeyframes.get(0); mLastKeyframe = mKeyframes.get(mNumKeyframes - 1); mInterpolator = mLastKeyframe.getInterpolator(); } public static KeyframeSet ofInt(int... values) { int numKeyframes = values.length; IntKeyframe keyframes[] = new IntKeyframe[Math.max(numKeyframes,2)]; if (numKeyframes == 1) { keyframes[0] = (IntKeyframe) Keyframe.ofInt(0f); keyframes[1] = (IntKeyframe) Keyframe.ofInt(1f, values[0]); } else { keyframes[0] = (IntKeyframe) Keyframe.ofInt(0f, values[0]); for (int i = 1; i < numKeyframes; ++i) { keyframes[i] = (IntKeyframe) Keyframe.ofInt((float) i / (numKeyframes - 1), values[i]); } } return new IntKeyframeSet(keyframes); } public static KeyframeSet ofFloat(float... values) { int numKeyframes = values.length; FloatKeyframe keyframes[] = new FloatKeyframe[Math.max(numKeyframes,2)]; if (numKeyframes == 1) { keyframes[0] = (FloatKeyframe) Keyframe.ofFloat(0f); keyframes[1] = (FloatKeyframe) Keyframe.ofFloat(1f, values[0]); } else { keyframes[0] = (FloatKeyframe) Keyframe.ofFloat(0f, values[0]); for (int i = 1; i < numKeyframes; ++i) { keyframes[i] = (FloatKeyframe) Keyframe.ofFloat((float) i / (numKeyframes - 1), values[i]); } } return new FloatKeyframeSet(keyframes); } public static KeyframeSet ofKeyframe(Keyframe... keyframes) { // if all keyframes of same primitive type, create the appropriate KeyframeSet int numKeyframes = keyframes.length; boolean hasFloat = false; boolean hasInt = false; boolean hasOther = false; for (int i = 0; i < numKeyframes; ++i) { if (keyframes[i] instanceof FloatKeyframe) { hasFloat = true; } else if (keyframes[i] instanceof IntKeyframe) { hasInt = true; } else { hasOther = true; } } if (hasFloat && !hasInt && !hasOther) { FloatKeyframe floatKeyframes[] = new FloatKeyframe[numKeyframes]; for (int i = 0; i < numKeyframes; ++i) { floatKeyframes[i] = (FloatKeyframe) keyframes[i]; } return new FloatKeyframeSet(floatKeyframes); } else if (hasInt && !hasFloat && !hasOther) { IntKeyframe intKeyframes[] = new IntKeyframe[numKeyframes]; for (int i = 0; i < numKeyframes; ++i) { intKeyframes[i] = (IntKeyframe) keyframes[i]; } return new IntKeyframeSet(intKeyframes); } else { return new KeyframeSet(keyframes); } } public static KeyframeSet ofObject(Object... values) { int numKeyframes = values.length; ObjectKeyframe keyframes[] = new ObjectKeyframe[Math.max(numKeyframes,2)]; if (numKeyframes == 1) { keyframes[0] = (ObjectKeyframe) Keyframe.ofObject(0f); keyframes[1] = (ObjectKeyframe) Keyframe.ofObject(1f, values[0]); } else { keyframes[0] = (ObjectKeyframe) Keyframe.ofObject(0f, values[0]); for (int i = 1; i < numKeyframes; ++i) { keyframes[i] = (ObjectKeyframe) Keyframe.ofObject((float) i / (numKeyframes - 1), values[i]); } } return new KeyframeSet(keyframes); } /** * Sets the TypeEvaluator to be used when calculating animated values. This object * is required only for KeyframeSets that are not either IntKeyframeSet or FloatKeyframeSet, * both of which assume their own evaluator to speed up calculations with those primitive * types. * * @param evaluator The TypeEvaluator to be used to calculate animated values. */ public void setEvaluator(TypeEvaluator evaluator) { mEvaluator = evaluator; } @Override public KeyframeSet clone() { ArrayList<Keyframe> keyframes = mKeyframes; int numKeyframes = mKeyframes.size(); Keyframe[] newKeyframes = new Keyframe[numKeyframes]; for (int i = 0; i < numKeyframes; ++i) { newKeyframes[i] = keyframes.get(i).clone(); } KeyframeSet newSet = new KeyframeSet(newKeyframes); return newSet; } /** * Gets the animated value, given the elapsed fraction of the animation (interpolated by the * animation's interpolator) and the evaluator used to calculate in-between values. This * function maps the input fraction to the appropriate keyframe interval and a fraction * between them and returns the interpolated value. Note that the input fraction may fall * outside the [0-1] bounds, if the animation's interpolator made that happen (e.g., a * spring interpolation that might send the fraction past 1.0). We handle this situation by * just using the two keyframes at the appropriate end when the value is outside those bounds. * * @param fraction The elapsed fraction of the animation * @return The animated value. */ public Object getValue(float fraction) { // Special-case optimization for the common case of only two keyframes if (mNumKeyframes == 2) { if (mInterpolator != null) { fraction = mInterpolator.getInterpolation(fraction); } return mEvaluator.evaluate(fraction, mFirstKeyframe.getValue(), mLastKeyframe.getValue()); } if (fraction <= 0f) { final Keyframe nextKeyframe = mKeyframes.get(1); final /*Time*/Interpolator interpolator = nextKeyframe.getInterpolator(); if (interpolator != null) { fraction = interpolator.getInterpolation(fraction); } final float prevFraction = mFirstKeyframe.getFraction(); float intervalFraction = (fraction - prevFraction) / (nextKeyframe.getFraction() - prevFraction); return mEvaluator.evaluate(intervalFraction, mFirstKeyframe.getValue(), nextKeyframe.getValue()); } else if (fraction >= 1f) { final Keyframe prevKeyframe = mKeyframes.get(mNumKeyframes - 2); final /*Time*/Interpolator interpolator = mLastKeyframe.getInterpolator(); if (interpolator != null) { fraction = interpolator.getInterpolation(fraction); } final float prevFraction = prevKeyframe.getFraction(); float intervalFraction = (fraction - prevFraction) / (mLastKeyframe.getFraction() - prevFraction); return mEvaluator.evaluate(intervalFraction, prevKeyframe.getValue(), mLastKeyframe.getValue()); } Keyframe prevKeyframe = mFirstKeyframe; for (int i = 1; i < mNumKeyframes; ++i) { Keyframe nextKeyframe = mKeyframes.get(i); if (fraction < nextKeyframe.getFraction()) { final /*Time*/Interpolator interpolator = nextKeyframe.getInterpolator(); if (interpolator != null) { fraction = interpolator.getInterpolation(fraction); } final float prevFraction = prevKeyframe.getFraction(); float intervalFraction = (fraction - prevFraction) / (nextKeyframe.getFraction() - prevFraction); return mEvaluator.evaluate(intervalFraction, prevKeyframe.getValue(), nextKeyframe.getValue()); } prevKeyframe = nextKeyframe; } // shouldn't reach here return mLastKeyframe.getValue(); } @Override public String toString() { String returnVal = " "; for (int i = 0; i < mNumKeyframes; ++i) { returnVal += mKeyframes.get(i).getValue() + " "; } return returnVal; } }
1162584980-google-io
libprojects/abs/src/com/actionbarsherlock/internal/nineoldandroids/animation/KeyframeSet.java
Java
asf20
9,920
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.actionbarsherlock.internal.nineoldandroids.animation; /** * This adapter class provides empty implementations of the methods from {@link android.animation.Animator.AnimatorListener}. * Any custom listener that cares only about a subset of the methods of this listener can * simply subclass this adapter class instead of implementing the interface directly. */ public abstract class AnimatorListenerAdapter implements Animator.AnimatorListener { /** * {@inheritDoc} */ @Override public void onAnimationCancel(Animator animation) { } /** * {@inheritDoc} */ @Override public void onAnimationEnd(Animator animation) { } /** * {@inheritDoc} */ @Override public void onAnimationRepeat(Animator animation) { } /** * {@inheritDoc} */ @Override public void onAnimationStart(Animator animation) { } }
1162584980-google-io
libprojects/abs/src/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorListenerAdapter.java
Java
asf20
1,538
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.actionbarsherlock.internal.nineoldandroids.animation; //import android.util.FloatProperty; //import android.util.IntProperty; import android.util.Log; //import android.util.Property; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * This class holds information about a property and the values that that property * should take on during an animation. PropertyValuesHolder objects can be used to create * animations with ValueAnimator or ObjectAnimator that operate on several different properties * in parallel. */ @SuppressWarnings({"rawtypes", "unchecked"}) public class PropertyValuesHolder implements Cloneable { /** * The name of the property associated with the values. This need not be a real property, * unless this object is being used with ObjectAnimator. But this is the name by which * aniamted values are looked up with getAnimatedValue(String) in ValueAnimator. */ String mPropertyName; /** * @hide */ //protected Property mProperty; /** * The setter function, if needed. ObjectAnimator hands off this functionality to * PropertyValuesHolder, since it holds all of the per-property information. This * property is automatically * derived when the animation starts in setupSetterAndGetter() if using ObjectAnimator. */ Method mSetter = null; /** * The getter function, if needed. ObjectAnimator hands off this functionality to * PropertyValuesHolder, since it holds all of the per-property information. This * property is automatically * derived when the animation starts in setupSetterAndGetter() if using ObjectAnimator. * The getter is only derived and used if one of the values is null. */ private Method mGetter = null; /** * The type of values supplied. This information is used both in deriving the setter/getter * functions and in deriving the type of TypeEvaluator. */ Class mValueType; /** * The set of keyframes (time/value pairs) that define this animation. */ KeyframeSet mKeyframeSet = null; // type evaluators for the primitive types handled by this implementation private static final TypeEvaluator sIntEvaluator = new IntEvaluator(); private static final TypeEvaluator sFloatEvaluator = new FloatEvaluator(); // We try several different types when searching for appropriate setter/getter functions. // The caller may have supplied values in a type that does not match the setter/getter // functions (such as the integers 0 and 1 to represent floating point values for alpha). // Also, the use of generics in constructors means that we end up with the Object versions // of primitive types (Float vs. float). But most likely, the setter/getter functions // will take primitive types instead. // So we supply an ordered array of other types to try before giving up. private static Class[] FLOAT_VARIANTS = {float.class, Float.class, double.class, int.class, Double.class, Integer.class}; private static Class[] INTEGER_VARIANTS = {int.class, Integer.class, float.class, double.class, Float.class, Double.class}; private static Class[] DOUBLE_VARIANTS = {double.class, Double.class, float.class, int.class, Float.class, Integer.class}; // These maps hold all property entries for a particular class. This map // is used to speed up property/setter/getter lookups for a given class/property // combination. No need to use reflection on the combination more than once. private static final HashMap<Class, HashMap<String, Method>> sSetterPropertyMap = new HashMap<Class, HashMap<String, Method>>(); private static final HashMap<Class, HashMap<String, Method>> sGetterPropertyMap = new HashMap<Class, HashMap<String, Method>>(); // This lock is used to ensure that only one thread is accessing the property maps // at a time. final ReentrantReadWriteLock mPropertyMapLock = new ReentrantReadWriteLock(); // Used to pass single value to varargs parameter in setter invocation final Object[] mTmpValueArray = new Object[1]; /** * The type evaluator used to calculate the animated values. This evaluator is determined * automatically based on the type of the start/end objects passed into the constructor, * but the system only knows about the primitive types int and float. Any other * type will need to set the evaluator to a custom evaluator for that type. */ private TypeEvaluator mEvaluator; /** * The value most recently calculated by calculateValue(). This is set during * that function and might be retrieved later either by ValueAnimator.animatedValue() or * by the property-setting logic in ObjectAnimator.animatedValue(). */ private Object mAnimatedValue; /** * Internal utility constructor, used by the factory methods to set the property name. * @param propertyName The name of the property for this holder. */ private PropertyValuesHolder(String propertyName) { mPropertyName = propertyName; } /** * Internal utility constructor, used by the factory methods to set the property. * @param property The property for this holder. */ //private PropertyValuesHolder(Property property) { // mProperty = property; // if (property != null) { // mPropertyName = property.getName(); // } //} /** * Constructs and returns a PropertyValuesHolder with a given property name and * set of int values. * @param propertyName The name of the property being animated. * @param values The values that the named property will animate between. * @return PropertyValuesHolder The constructed PropertyValuesHolder object. */ public static PropertyValuesHolder ofInt(String propertyName, int... values) { return new IntPropertyValuesHolder(propertyName, values); } /** * Constructs and returns a PropertyValuesHolder with a given property and * set of int values. * @param property The property being animated. Should not be null. * @param values The values that the property will animate between. * @return PropertyValuesHolder The constructed PropertyValuesHolder object. */ //public static PropertyValuesHolder ofInt(Property<?, Integer> property, int... values) { // return new IntPropertyValuesHolder(property, values); //} /** * Constructs and returns a PropertyValuesHolder with a given property name and * set of float values. * @param propertyName The name of the property being animated. * @param values The values that the named property will animate between. * @return PropertyValuesHolder The constructed PropertyValuesHolder object. */ public static PropertyValuesHolder ofFloat(String propertyName, float... values) { return new FloatPropertyValuesHolder(propertyName, values); } /** * Constructs and returns a PropertyValuesHolder with a given property and * set of float values. * @param property The property being animated. Should not be null. * @param values The values that the property will animate between. * @return PropertyValuesHolder The constructed PropertyValuesHolder object. */ //public static PropertyValuesHolder ofFloat(Property<?, Float> property, float... values) { // return new FloatPropertyValuesHolder(property, values); //} /** * Constructs and returns a PropertyValuesHolder with a given property name and * set of Object values. This variant also takes a TypeEvaluator because the system * cannot automatically interpolate between objects of unknown type. * * @param propertyName The name of the property being animated. * @param evaluator A TypeEvaluator that will be called on each animation frame to * provide the necessary interpolation between the Object values to derive the animated * value. * @param values The values that the named property will animate between. * @return PropertyValuesHolder The constructed PropertyValuesHolder object. */ public static PropertyValuesHolder ofObject(String propertyName, TypeEvaluator evaluator, Object... values) { PropertyValuesHolder pvh = new PropertyValuesHolder(propertyName); pvh.setObjectValues(values); pvh.setEvaluator(evaluator); return pvh; } /** * Constructs and returns a PropertyValuesHolder with a given property and * set of Object values. This variant also takes a TypeEvaluator because the system * cannot automatically interpolate between objects of unknown type. * * @param property The property being animated. Should not be null. * @param evaluator A TypeEvaluator that will be called on each animation frame to * provide the necessary interpolation between the Object values to derive the animated * value. * @param values The values that the property will animate between. * @return PropertyValuesHolder The constructed PropertyValuesHolder object. */ //public static <V> PropertyValuesHolder ofObject(Property property, // TypeEvaluator<V> evaluator, V... values) { // PropertyValuesHolder pvh = new PropertyValuesHolder(property); // pvh.setObjectValues(values); // pvh.setEvaluator(evaluator); // return pvh; //} /** * Constructs and returns a PropertyValuesHolder object with the specified property name and set * of values. These values can be of any type, but the type should be consistent so that * an appropriate {@link android.animation.TypeEvaluator} can be found that matches * the common type. * <p>If there is only one value, it is assumed to be the end value of an animation, * and an initial value will be derived, if possible, by calling a getter function * on the object. Also, if any value is null, the value will be filled in when the animation * starts in the same way. This mechanism of automatically getting null values only works * if the PropertyValuesHolder object is used in conjunction * {@link ObjectAnimator}, and with a getter function * derived automatically from <code>propertyName</code>, since otherwise PropertyValuesHolder has * no way of determining what the value should be. * @param propertyName The name of the property associated with this set of values. This * can be the actual property name to be used when using a ObjectAnimator object, or * just a name used to get animated values, such as if this object is used with an * ValueAnimator object. * @param values The set of values to animate between. */ public static PropertyValuesHolder ofKeyframe(String propertyName, Keyframe... values) { KeyframeSet keyframeSet = KeyframeSet.ofKeyframe(values); if (keyframeSet instanceof IntKeyframeSet) { return new IntPropertyValuesHolder(propertyName, (IntKeyframeSet) keyframeSet); } else if (keyframeSet instanceof FloatKeyframeSet) { return new FloatPropertyValuesHolder(propertyName, (FloatKeyframeSet) keyframeSet); } else { PropertyValuesHolder pvh = new PropertyValuesHolder(propertyName); pvh.mKeyframeSet = keyframeSet; pvh.mValueType = values[0].getType(); return pvh; } } /** * Constructs and returns a PropertyValuesHolder object with the specified property and set * of values. These values can be of any type, but the type should be consistent so that * an appropriate {@link android.animation.TypeEvaluator} can be found that matches * the common type. * <p>If there is only one value, it is assumed to be the end value of an animation, * and an initial value will be derived, if possible, by calling the property's * {@link android.util.Property#get(Object)} function. * Also, if any value is null, the value will be filled in when the animation * starts in the same way. This mechanism of automatically getting null values only works * if the PropertyValuesHolder object is used in conjunction with * {@link ObjectAnimator}, since otherwise PropertyValuesHolder has * no way of determining what the value should be. * @param property The property associated with this set of values. Should not be null. * @param values The set of values to animate between. */ //public static PropertyValuesHolder ofKeyframe(Property property, Keyframe... values) { // KeyframeSet keyframeSet = KeyframeSet.ofKeyframe(values); // if (keyframeSet instanceof IntKeyframeSet) { // return new IntPropertyValuesHolder(property, (IntKeyframeSet) keyframeSet); // } else if (keyframeSet instanceof FloatKeyframeSet) { // return new FloatPropertyValuesHolder(property, (FloatKeyframeSet) keyframeSet); // } // else { // PropertyValuesHolder pvh = new PropertyValuesHolder(property); // pvh.mKeyframeSet = keyframeSet; // pvh.mValueType = ((Keyframe)values[0]).getType(); // return pvh; // } //} /** * Set the animated values for this object to this set of ints. * If there is only one value, it is assumed to be the end value of an animation, * and an initial value will be derived, if possible, by calling a getter function * on the object. Also, if any value is null, the value will be filled in when the animation * starts in the same way. This mechanism of automatically getting null values only works * if the PropertyValuesHolder object is used in conjunction * {@link ObjectAnimator}, and with a getter function * derived automatically from <code>propertyName</code>, since otherwise PropertyValuesHolder has * no way of determining what the value should be. * * @param values One or more values that the animation will animate between. */ public void setIntValues(int... values) { mValueType = int.class; mKeyframeSet = KeyframeSet.ofInt(values); } /** * Set the animated values for this object to this set of floats. * If there is only one value, it is assumed to be the end value of an animation, * and an initial value will be derived, if possible, by calling a getter function * on the object. Also, if any value is null, the value will be filled in when the animation * starts in the same way. This mechanism of automatically getting null values only works * if the PropertyValuesHolder object is used in conjunction * {@link ObjectAnimator}, and with a getter function * derived automatically from <code>propertyName</code>, since otherwise PropertyValuesHolder has * no way of determining what the value should be. * * @param values One or more values that the animation will animate between. */ public void setFloatValues(float... values) { mValueType = float.class; mKeyframeSet = KeyframeSet.ofFloat(values); } /** * Set the animated values for this object to this set of Keyframes. * * @param values One or more values that the animation will animate between. */ public void setKeyframes(Keyframe... values) { int numKeyframes = values.length; Keyframe keyframes[] = new Keyframe[Math.max(numKeyframes,2)]; mValueType = values[0].getType(); for (int i = 0; i < numKeyframes; ++i) { keyframes[i] = values[i]; } mKeyframeSet = new KeyframeSet(keyframes); } /** * Set the animated values for this object to this set of Objects. * If there is only one value, it is assumed to be the end value of an animation, * and an initial value will be derived, if possible, by calling a getter function * on the object. Also, if any value is null, the value will be filled in when the animation * starts in the same way. This mechanism of automatically getting null values only works * if the PropertyValuesHolder object is used in conjunction * {@link ObjectAnimator}, and with a getter function * derived automatically from <code>propertyName</code>, since otherwise PropertyValuesHolder has * no way of determining what the value should be. * * @param values One or more values that the animation will animate between. */ public void setObjectValues(Object... values) { mValueType = values[0].getClass(); mKeyframeSet = KeyframeSet.ofObject(values); } /** * Determine the setter or getter function using the JavaBeans convention of setFoo or * getFoo for a property named 'foo'. This function figures out what the name of the * function should be and uses reflection to find the Method with that name on the * target object. * * @param targetClass The class to search for the method * @param prefix "set" or "get", depending on whether we need a setter or getter. * @param valueType The type of the parameter (in the case of a setter). This type * is derived from the values set on this PropertyValuesHolder. This type is used as * a first guess at the parameter type, but we check for methods with several different * types to avoid problems with slight mis-matches between supplied values and actual * value types used on the setter. * @return Method the method associated with mPropertyName. */ private Method getPropertyFunction(Class targetClass, String prefix, Class valueType) { // TODO: faster implementation... Method returnVal = null; String methodName = getMethodName(prefix, mPropertyName); Class args[] = null; if (valueType == null) { try { returnVal = targetClass.getMethod(methodName, args); } catch (NoSuchMethodException e) { Log.e("PropertyValuesHolder", targetClass.getSimpleName() + " - " + "Couldn't find no-arg method for property " + mPropertyName + ": " + e); } } else { args = new Class[1]; Class typeVariants[]; if (mValueType.equals(Float.class)) { typeVariants = FLOAT_VARIANTS; } else if (mValueType.equals(Integer.class)) { typeVariants = INTEGER_VARIANTS; } else if (mValueType.equals(Double.class)) { typeVariants = DOUBLE_VARIANTS; } else { typeVariants = new Class[1]; typeVariants[0] = mValueType; } for (Class typeVariant : typeVariants) { args[0] = typeVariant; try { returnVal = targetClass.getMethod(methodName, args); // change the value type to suit mValueType = typeVariant; return returnVal; } catch (NoSuchMethodException e) { // Swallow the error and keep trying other variants } } // If we got here, then no appropriate function was found Log.e("PropertyValuesHolder", "Couldn't find " + prefix + "ter property " + mPropertyName + " for " + targetClass.getSimpleName() + " with value type "+ mValueType); } return returnVal; } /** * Returns the setter or getter requested. This utility function checks whether the * requested method exists in the propertyMapMap cache. If not, it calls another * utility function to request the Method from the targetClass directly. * @param targetClass The Class on which the requested method should exist. * @param propertyMapMap The cache of setters/getters derived so far. * @param prefix "set" or "get", for the setter or getter. * @param valueType The type of parameter passed into the method (null for getter). * @return Method the method associated with mPropertyName. */ private Method setupSetterOrGetter(Class targetClass, HashMap<Class, HashMap<String, Method>> propertyMapMap, String prefix, Class valueType) { Method setterOrGetter = null; try { // Have to lock property map prior to reading it, to guard against // another thread putting something in there after we've checked it // but before we've added an entry to it mPropertyMapLock.writeLock().lock(); HashMap<String, Method> propertyMap = propertyMapMap.get(targetClass); if (propertyMap != null) { setterOrGetter = propertyMap.get(mPropertyName); } if (setterOrGetter == null) { setterOrGetter = getPropertyFunction(targetClass, prefix, valueType); if (propertyMap == null) { propertyMap = new HashMap<String, Method>(); propertyMapMap.put(targetClass, propertyMap); } propertyMap.put(mPropertyName, setterOrGetter); } } finally { mPropertyMapLock.writeLock().unlock(); } return setterOrGetter; } /** * Utility function to get the setter from targetClass * @param targetClass The Class on which the requested method should exist. */ void setupSetter(Class targetClass) { mSetter = setupSetterOrGetter(targetClass, sSetterPropertyMap, "set", mValueType); } /** * Utility function to get the getter from targetClass */ private void setupGetter(Class targetClass) { mGetter = setupSetterOrGetter(targetClass, sGetterPropertyMap, "get", null); } /** * Internal function (called from ObjectAnimator) to set up the setter and getter * prior to running the animation. If the setter has not been manually set for this * object, it will be derived automatically given the property name, target object, and * types of values supplied. If no getter has been set, it will be supplied iff any of the * supplied values was null. If there is a null value, then the getter (supplied or derived) * will be called to set those null values to the current value of the property * on the target object. * @param target The object on which the setter (and possibly getter) exist. */ void setupSetterAndGetter(Object target) { //if (mProperty != null) { // // check to make sure that mProperty is on the class of target // try { // Object testValue = mProperty.get(target); // for (Keyframe kf : mKeyframeSet.mKeyframes) { // if (!kf.hasValue()) { // kf.setValue(mProperty.get(target)); // } // } // return; // } catch (ClassCastException e) { // Log.e("PropertyValuesHolder","No such property (" + mProperty.getName() + // ") on target object " + target + ". Trying reflection instead"); // mProperty = null; // } //} Class targetClass = target.getClass(); if (mSetter == null) { setupSetter(targetClass); } for (Keyframe kf : mKeyframeSet.mKeyframes) { if (!kf.hasValue()) { if (mGetter == null) { setupGetter(targetClass); } try { kf.setValue(mGetter.invoke(target)); } catch (InvocationTargetException e) { Log.e("PropertyValuesHolder", e.toString()); } catch (IllegalAccessException e) { Log.e("PropertyValuesHolder", e.toString()); } } } } /** * Utility function to set the value stored in a particular Keyframe. The value used is * whatever the value is for the property name specified in the keyframe on the target object. * * @param target The target object from which the current value should be extracted. * @param kf The keyframe which holds the property name and value. */ private void setupValue(Object target, Keyframe kf) { //if (mProperty != null) { // kf.setValue(mProperty.get(target)); //} try { if (mGetter == null) { Class targetClass = target.getClass(); setupGetter(targetClass); } kf.setValue(mGetter.invoke(target)); } catch (InvocationTargetException e) { Log.e("PropertyValuesHolder", e.toString()); } catch (IllegalAccessException e) { Log.e("PropertyValuesHolder", e.toString()); } } /** * This function is called by ObjectAnimator when setting the start values for an animation. * The start values are set according to the current values in the target object. The * property whose value is extracted is whatever is specified by the propertyName of this * PropertyValuesHolder object. * * @param target The object which holds the start values that should be set. */ void setupStartValue(Object target) { setupValue(target, mKeyframeSet.mKeyframes.get(0)); } /** * This function is called by ObjectAnimator when setting the end values for an animation. * The end values are set according to the current values in the target object. The * property whose value is extracted is whatever is specified by the propertyName of this * PropertyValuesHolder object. * * @param target The object which holds the start values that should be set. */ void setupEndValue(Object target) { setupValue(target, mKeyframeSet.mKeyframes.get(mKeyframeSet.mKeyframes.size() - 1)); } @Override public PropertyValuesHolder clone() { try { PropertyValuesHolder newPVH = (PropertyValuesHolder) super.clone(); newPVH.mPropertyName = mPropertyName; //newPVH.mProperty = mProperty; newPVH.mKeyframeSet = mKeyframeSet.clone(); newPVH.mEvaluator = mEvaluator; return newPVH; } catch (CloneNotSupportedException e) { // won't reach here return null; } } /** * Internal function to set the value on the target object, using the setter set up * earlier on this PropertyValuesHolder object. This function is called by ObjectAnimator * to handle turning the value calculated by ValueAnimator into a value set on the object * according to the name of the property. * @param target The target object on which the value is set */ void setAnimatedValue(Object target) { //if (mProperty != null) { // mProperty.set(target, getAnimatedValue()); //} if (mSetter != null) { try { mTmpValueArray[0] = getAnimatedValue(); mSetter.invoke(target, mTmpValueArray); } catch (InvocationTargetException e) { Log.e("PropertyValuesHolder", e.toString()); } catch (IllegalAccessException e) { Log.e("PropertyValuesHolder", e.toString()); } } } /** * Internal function, called by ValueAnimator, to set up the TypeEvaluator that will be used * to calculate animated values. */ void init() { if (mEvaluator == null) { // We already handle int and float automatically, but not their Object // equivalents mEvaluator = (mValueType == Integer.class) ? sIntEvaluator : (mValueType == Float.class) ? sFloatEvaluator : null; } if (mEvaluator != null) { // KeyframeSet knows how to evaluate the common types - only give it a custom // evaluator if one has been set on this class mKeyframeSet.setEvaluator(mEvaluator); } } /** * The TypeEvaluator will the automatically determined based on the type of values * supplied to PropertyValuesHolder. The evaluator can be manually set, however, if so * desired. This may be important in cases where either the type of the values supplied * do not match the way that they should be interpolated between, or if the values * are of a custom type or one not currently understood by the animation system. Currently, * only values of type float and int (and their Object equivalents: Float * and Integer) are correctly interpolated; all other types require setting a TypeEvaluator. * @param evaluator */ public void setEvaluator(TypeEvaluator evaluator) { mEvaluator = evaluator; mKeyframeSet.setEvaluator(evaluator); } /** * Function used to calculate the value according to the evaluator set up for * this PropertyValuesHolder object. This function is called by ValueAnimator.animateValue(). * * @param fraction The elapsed, interpolated fraction of the animation. */ void calculateValue(float fraction) { mAnimatedValue = mKeyframeSet.getValue(fraction); } /** * Sets the name of the property that will be animated. This name is used to derive * a setter function that will be called to set animated values. * For example, a property name of <code>foo</code> will result * in a call to the function <code>setFoo()</code> on the target object. If either * <code>valueFrom</code> or <code>valueTo</code> is null, then a getter function will * also be derived and called. * * <p>Note that the setter function derived from this property name * must take the same parameter type as the * <code>valueFrom</code> and <code>valueTo</code> properties, otherwise the call to * the setter function will fail.</p> * * @param propertyName The name of the property being animated. */ public void setPropertyName(String propertyName) { mPropertyName = propertyName; } /** * Sets the property that will be animated. * * <p>Note that if this PropertyValuesHolder object is used with ObjectAnimator, the property * must exist on the target object specified in that ObjectAnimator.</p> * * @param property The property being animated. */ //public void setProperty(Property property) { // mProperty = property; //} /** * Gets the name of the property that will be animated. This name will be used to derive * a setter function that will be called to set animated values. * For example, a property name of <code>foo</code> will result * in a call to the function <code>setFoo()</code> on the target object. If either * <code>valueFrom</code> or <code>valueTo</code> is null, then a getter function will * also be derived and called. */ public String getPropertyName() { return mPropertyName; } /** * Internal function, called by ValueAnimator and ObjectAnimator, to retrieve the value * most recently calculated in calculateValue(). * @return */ Object getAnimatedValue() { return mAnimatedValue; } @Override public String toString() { return mPropertyName + ": " + mKeyframeSet.toString(); } /** * Utility method to derive a setter/getter method name from a property name, where the * prefix is typically "set" or "get" and the first letter of the property name is * capitalized. * * @param prefix The precursor to the method name, before the property name begins, typically * "set" or "get". * @param propertyName The name of the property that represents the bulk of the method name * after the prefix. The first letter of this word will be capitalized in the resulting * method name. * @return String the property name converted to a method name according to the conventions * specified above. */ static String getMethodName(String prefix, String propertyName) { if (propertyName == null || propertyName.length() == 0) { // shouldn't get here return prefix; } char firstLetter = Character.toUpperCase(propertyName.charAt(0)); String theRest = propertyName.substring(1); return prefix + firstLetter + theRest; } static class IntPropertyValuesHolder extends PropertyValuesHolder { // Cache JNI functions to avoid looking them up twice //private static final HashMap<Class, HashMap<String, Integer>> sJNISetterPropertyMap = // new HashMap<Class, HashMap<String, Integer>>(); //int mJniSetter; //private IntProperty mIntProperty; IntKeyframeSet mIntKeyframeSet; int mIntAnimatedValue; public IntPropertyValuesHolder(String propertyName, IntKeyframeSet keyframeSet) { super(propertyName); mValueType = int.class; mKeyframeSet = keyframeSet; mIntKeyframeSet = (IntKeyframeSet) mKeyframeSet; } //public IntPropertyValuesHolder(Property property, IntKeyframeSet keyframeSet) { // super(property); // mValueType = int.class; // mKeyframeSet = keyframeSet; // mIntKeyframeSet = (IntKeyframeSet) mKeyframeSet; // if (property instanceof IntProperty) { // mIntProperty = (IntProperty) mProperty; // } //} public IntPropertyValuesHolder(String propertyName, int... values) { super(propertyName); setIntValues(values); } //public IntPropertyValuesHolder(Property property, int... values) { // super(property); // setIntValues(values); // if (property instanceof IntProperty) { // mIntProperty = (IntProperty) mProperty; // } //} @Override public void setIntValues(int... values) { super.setIntValues(values); mIntKeyframeSet = (IntKeyframeSet) mKeyframeSet; } @Override void calculateValue(float fraction) { mIntAnimatedValue = mIntKeyframeSet.getIntValue(fraction); } @Override Object getAnimatedValue() { return mIntAnimatedValue; } @Override public IntPropertyValuesHolder clone() { IntPropertyValuesHolder newPVH = (IntPropertyValuesHolder) super.clone(); newPVH.mIntKeyframeSet = (IntKeyframeSet) newPVH.mKeyframeSet; return newPVH; } /** * Internal function to set the value on the target object, using the setter set up * earlier on this PropertyValuesHolder object. This function is called by ObjectAnimator * to handle turning the value calculated by ValueAnimator into a value set on the object * according to the name of the property. * @param target The target object on which the value is set */ @Override void setAnimatedValue(Object target) { //if (mIntProperty != null) { // mIntProperty.setValue(target, mIntAnimatedValue); // return; //} //if (mProperty != null) { // mProperty.set(target, mIntAnimatedValue); // return; //} //if (mJniSetter != 0) { // nCallIntMethod(target, mJniSetter, mIntAnimatedValue); // return; //} if (mSetter != null) { try { mTmpValueArray[0] = mIntAnimatedValue; mSetter.invoke(target, mTmpValueArray); } catch (InvocationTargetException e) { Log.e("PropertyValuesHolder", e.toString()); } catch (IllegalAccessException e) { Log.e("PropertyValuesHolder", e.toString()); } } } @Override void setupSetter(Class targetClass) { //if (mProperty != null) { // return; //} // Check new static hashmap<propName, int> for setter method //try { // mPropertyMapLock.writeLock().lock(); // HashMap<String, Integer> propertyMap = sJNISetterPropertyMap.get(targetClass); // if (propertyMap != null) { // Integer mJniSetterInteger = propertyMap.get(mPropertyName); // if (mJniSetterInteger != null) { // mJniSetter = mJniSetterInteger; // } // } // if (mJniSetter == 0) { // String methodName = getMethodName("set", mPropertyName); // mJniSetter = nGetIntMethod(targetClass, methodName); // if (mJniSetter != 0) { // if (propertyMap == null) { // propertyMap = new HashMap<String, Integer>(); // sJNISetterPropertyMap.put(targetClass, propertyMap); // } // propertyMap.put(mPropertyName, mJniSetter); // } // } //} catch (NoSuchMethodError e) { // Log.d("PropertyValuesHolder", // "Can't find native method using JNI, use reflection" + e); //} finally { // mPropertyMapLock.writeLock().unlock(); //} //if (mJniSetter == 0) { // Couldn't find method through fast JNI approach - just use reflection super.setupSetter(targetClass); //} } } static class FloatPropertyValuesHolder extends PropertyValuesHolder { // Cache JNI functions to avoid looking them up twice //private static final HashMap<Class, HashMap<String, Integer>> sJNISetterPropertyMap = // new HashMap<Class, HashMap<String, Integer>>(); //int mJniSetter; //private FloatProperty mFloatProperty; FloatKeyframeSet mFloatKeyframeSet; float mFloatAnimatedValue; public FloatPropertyValuesHolder(String propertyName, FloatKeyframeSet keyframeSet) { super(propertyName); mValueType = float.class; mKeyframeSet = keyframeSet; mFloatKeyframeSet = (FloatKeyframeSet) mKeyframeSet; } //public FloatPropertyValuesHolder(Property property, FloatKeyframeSet keyframeSet) { // super(property); // mValueType = float.class; // mKeyframeSet = keyframeSet; // mFloatKeyframeSet = (FloatKeyframeSet) mKeyframeSet; // if (property instanceof FloatProperty) { // mFloatProperty = (FloatProperty) mProperty; // } //} public FloatPropertyValuesHolder(String propertyName, float... values) { super(propertyName); setFloatValues(values); } //public FloatPropertyValuesHolder(Property property, float... values) { // super(property); // setFloatValues(values); // if (property instanceof FloatProperty) { // mFloatProperty = (FloatProperty) mProperty; // } //} @Override public void setFloatValues(float... values) { super.setFloatValues(values); mFloatKeyframeSet = (FloatKeyframeSet) mKeyframeSet; } @Override void calculateValue(float fraction) { mFloatAnimatedValue = mFloatKeyframeSet.getFloatValue(fraction); } @Override Object getAnimatedValue() { return mFloatAnimatedValue; } @Override public FloatPropertyValuesHolder clone() { FloatPropertyValuesHolder newPVH = (FloatPropertyValuesHolder) super.clone(); newPVH.mFloatKeyframeSet = (FloatKeyframeSet) newPVH.mKeyframeSet; return newPVH; } /** * Internal function to set the value on the target object, using the setter set up * earlier on this PropertyValuesHolder object. This function is called by ObjectAnimator * to handle turning the value calculated by ValueAnimator into a value set on the object * according to the name of the property. * @param target The target object on which the value is set */ @Override void setAnimatedValue(Object target) { //if (mFloatProperty != null) { // mFloatProperty.setValue(target, mFloatAnimatedValue); // return; //} //if (mProperty != null) { // mProperty.set(target, mFloatAnimatedValue); // return; //} //if (mJniSetter != 0) { // nCallFloatMethod(target, mJniSetter, mFloatAnimatedValue); // return; //} if (mSetter != null) { try { mTmpValueArray[0] = mFloatAnimatedValue; mSetter.invoke(target, mTmpValueArray); } catch (InvocationTargetException e) { Log.e("PropertyValuesHolder", e.toString()); } catch (IllegalAccessException e) { Log.e("PropertyValuesHolder", e.toString()); } } } @Override void setupSetter(Class targetClass) { //if (mProperty != null) { // return; //} // Check new static hashmap<propName, int> for setter method //try { // mPropertyMapLock.writeLock().lock(); // HashMap<String, Integer> propertyMap = sJNISetterPropertyMap.get(targetClass); // if (propertyMap != null) { // Integer mJniSetterInteger = propertyMap.get(mPropertyName); // if (mJniSetterInteger != null) { // mJniSetter = mJniSetterInteger; // } // } // if (mJniSetter == 0) { // String methodName = getMethodName("set", mPropertyName); // mJniSetter = nGetFloatMethod(targetClass, methodName); // if (mJniSetter != 0) { // if (propertyMap == null) { // propertyMap = new HashMap<String, Integer>(); // sJNISetterPropertyMap.put(targetClass, propertyMap); // } // propertyMap.put(mPropertyName, mJniSetter); // } // } //} catch (NoSuchMethodError e) { // Log.d("PropertyValuesHolder", // "Can't find native method using JNI, use reflection" + e); //} finally { // mPropertyMapLock.writeLock().unlock(); //} //if (mJniSetter == 0) { // Couldn't find method through fast JNI approach - just use reflection super.setupSetter(targetClass); //} } } //native static private int nGetIntMethod(Class targetClass, String methodName); //native static private int nGetFloatMethod(Class targetClass, String methodName); //native static private void nCallIntMethod(Object target, int methodID, int arg); //native static private void nCallFloatMethod(Object target, int methodID, float arg); }
1162584980-google-io
libprojects/abs/src/com/actionbarsherlock/internal/nineoldandroids/animation/PropertyValuesHolder.java
Java
asf20
44,887
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.actionbarsherlock.internal.nineoldandroids.animation; /** * Interface for use with the {@link ValueAnimator#setEvaluator(TypeEvaluator)} function. Evaluators * allow developers to create animations on arbitrary property types, by allowing them to supply * custom evaulators for types that are not automatically understood and used by the animation * system. * * @see ValueAnimator#setEvaluator(TypeEvaluator) */ public interface TypeEvaluator<T> { /** * This function returns the result of linearly interpolating the start and end values, with * <code>fraction</code> representing the proportion between the start and end values. The * calculation is a simple parametric calculation: <code>result = x0 + t * (v1 - v0)</code>, * where <code>x0</code> is <code>startValue</code>, <code>x1</code> is <code>endValue</code>, * and <code>t</code> is <code>fraction</code>. * * @param fraction The fraction from the starting to the ending values * @param startValue The start value. * @param endValue The end value. * @return A linear interpolation between the start and end values, given the * <code>fraction</code> parameter. */ public T evaluate(float fraction, T startValue, T endValue); }
1162584980-google-io
libprojects/abs/src/com/actionbarsherlock/internal/nineoldandroids/animation/TypeEvaluator.java
Java
asf20
1,909
package com.actionbarsherlock.internal.nineoldandroids.view.animation; import java.lang.ref.WeakReference; import java.util.WeakHashMap; import android.graphics.Matrix; import android.graphics.RectF; import android.os.Build; import android.util.FloatMath; import android.view.View; import android.view.animation.Animation; import android.view.animation.Transformation; public final class AnimatorProxy extends Animation { public static final boolean NEEDS_PROXY = Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB; private static final WeakHashMap<View, AnimatorProxy> PROXIES = new WeakHashMap<View, AnimatorProxy>(); public static AnimatorProxy wrap(View view) { AnimatorProxy proxy = PROXIES.get(view); if (proxy == null) { proxy = new AnimatorProxy(view); PROXIES.put(view, proxy); } return proxy; } private final WeakReference<View> mView; private float mAlpha = 1; private float mScaleX = 1; private float mScaleY = 1; private float mTranslationX; private float mTranslationY; private final RectF mBefore = new RectF(); private final RectF mAfter = new RectF(); private final Matrix mTempMatrix = new Matrix(); private AnimatorProxy(View view) { setDuration(0); //perform transformation immediately setFillAfter(true); //persist transformation beyond duration view.setAnimation(this); mView = new WeakReference<View>(view); } public float getAlpha() { return mAlpha; } public void setAlpha(float alpha) { if (mAlpha != alpha) { mAlpha = alpha; View view = mView.get(); if (view != null) { view.invalidate(); } } } public float getScaleX() { return mScaleX; } public void setScaleX(float scaleX) { if (mScaleX != scaleX) { prepareForUpdate(); mScaleX = scaleX; invalidateAfterUpdate(); } } public float getScaleY() { return mScaleY; } public void setScaleY(float scaleY) { if (mScaleY != scaleY) { prepareForUpdate(); mScaleY = scaleY; invalidateAfterUpdate(); } } public int getScrollX() { View view = mView.get(); if (view == null) { return 0; } return view.getScrollX(); } public void setScrollX(int value) { View view = mView.get(); if (view != null) { view.scrollTo(value, view.getScrollY()); } } public int getScrollY() { View view = mView.get(); if (view == null) { return 0; } return view.getScrollY(); } public void setScrollY(int value) { View view = mView.get(); if (view != null) { view.scrollTo(view.getScrollY(), value); } } public float getTranslationX() { return mTranslationX; } public void setTranslationX(float translationX) { if (mTranslationX != translationX) { prepareForUpdate(); mTranslationX = translationX; invalidateAfterUpdate(); } } public float getTranslationY() { return mTranslationY; } public void setTranslationY(float translationY) { if (mTranslationY != translationY) { prepareForUpdate(); mTranslationY = translationY; invalidateAfterUpdate(); } } private void prepareForUpdate() { View view = mView.get(); if (view != null) { computeRect(mBefore, view); } } private void invalidateAfterUpdate() { View view = mView.get(); if (view == null) { return; } View parent = (View)view.getParent(); if (parent == null) { return; } view.setAnimation(this); final RectF after = mAfter; computeRect(after, view); after.union(mBefore); parent.invalidate( (int) FloatMath.floor(after.left), (int) FloatMath.floor(after.top), (int) FloatMath.ceil(after.right), (int) FloatMath.ceil(after.bottom)); } private void computeRect(final RectF r, View view) { // compute current rectangle according to matrix transformation final float w = view.getWidth(); final float h = view.getHeight(); // use a rectangle at 0,0 to make sure we don't run into issues with scaling r.set(0, 0, w, h); final Matrix m = mTempMatrix; m.reset(); transformMatrix(m, view); mTempMatrix.mapRect(r); r.offset(view.getLeft(), view.getTop()); // Straighten coords if rotations flipped them if (r.right < r.left) { final float f = r.right; r.right = r.left; r.left = f; } if (r.bottom < r.top) { final float f = r.top; r.top = r.bottom; r.bottom = f; } } private void transformMatrix(Matrix m, View view) { final float w = view.getWidth(); final float h = view.getHeight(); final float sX = mScaleX; final float sY = mScaleY; if ((sX != 1.0f) || (sY != 1.0f)) { final float deltaSX = ((sX * w) - w) / 2f; final float deltaSY = ((sY * h) - h) / 2f; m.postScale(sX, sY); m.postTranslate(-deltaSX, -deltaSY); } m.postTranslate(mTranslationX, mTranslationY); } @Override protected void applyTransformation(float interpolatedTime, Transformation t) { View view = mView.get(); if (view != null) { t.setAlpha(mAlpha); transformMatrix(t.getMatrix(), view); } } @Override public void reset() { /* Do nothing. */ } }
1162584980-google-io
libprojects/abs/src/com/actionbarsherlock/internal/nineoldandroids/view/animation/AnimatorProxy.java
Java
asf20
6,010
package com.actionbarsherlock.internal.nineoldandroids.view; import android.content.Context; import android.util.AttributeSet; import android.view.ViewGroup; import com.actionbarsherlock.internal.nineoldandroids.view.animation.AnimatorProxy; public abstract class NineViewGroup extends ViewGroup { private final AnimatorProxy mProxy; public NineViewGroup(Context context) { super(context); mProxy = AnimatorProxy.NEEDS_PROXY ? AnimatorProxy.wrap(this) : null; } public NineViewGroup(Context context, AttributeSet attrs) { super(context, attrs); mProxy = AnimatorProxy.NEEDS_PROXY ? AnimatorProxy.wrap(this) : null; } public NineViewGroup(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mProxy = AnimatorProxy.NEEDS_PROXY ? AnimatorProxy.wrap(this) : null; } @Override public void setVisibility(int visibility) { if (mProxy != null) { if (visibility == GONE) { clearAnimation(); } else if (visibility == VISIBLE) { setAnimation(mProxy); } } super.setVisibility(visibility); } public float getAlpha() { if (AnimatorProxy.NEEDS_PROXY) { return mProxy.getAlpha(); } else { return super.getAlpha(); } } public void setAlpha(float alpha) { if (AnimatorProxy.NEEDS_PROXY) { mProxy.setAlpha(alpha); } else { super.setAlpha(alpha); } } public float getTranslationX() { if (AnimatorProxy.NEEDS_PROXY) { return mProxy.getTranslationX(); } else { return super.getTranslationX(); } } public void setTranslationX(float translationX) { if (AnimatorProxy.NEEDS_PROXY) { mProxy.setTranslationX(translationX); } else { super.setTranslationX(translationX); } } public float getTranslationY() { if (AnimatorProxy.NEEDS_PROXY) { return mProxy.getTranslationY(); } else { return super.getTranslationY(); } } public void setTranslationY(float translationY) { if (AnimatorProxy.NEEDS_PROXY) { mProxy.setTranslationY(translationY); } else { super.setTranslationY(translationY); } } }
1162584980-google-io
libprojects/abs/src/com/actionbarsherlock/internal/nineoldandroids/view/NineViewGroup.java
Java
asf20
2,419
package com.actionbarsherlock.internal.nineoldandroids.widget; import android.content.Context; import android.util.AttributeSet; import android.widget.FrameLayout; import com.actionbarsherlock.internal.nineoldandroids.view.animation.AnimatorProxy; public class NineFrameLayout extends FrameLayout { private final AnimatorProxy mProxy; public NineFrameLayout(Context context) { super(context); mProxy = AnimatorProxy.NEEDS_PROXY ? AnimatorProxy.wrap(this) : null; } public NineFrameLayout(Context context, AttributeSet attrs) { super(context, attrs); mProxy = AnimatorProxy.NEEDS_PROXY ? AnimatorProxy.wrap(this) : null; } public NineFrameLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mProxy = AnimatorProxy.NEEDS_PROXY ? AnimatorProxy.wrap(this) : null; } @Override public void setVisibility(int visibility) { if (mProxy != null) { if (visibility == GONE) { clearAnimation(); } else if (visibility == VISIBLE) { setAnimation(mProxy); } } super.setVisibility(visibility); } public float getAlpha() { if (AnimatorProxy.NEEDS_PROXY) { return mProxy.getAlpha(); } else { return super.getAlpha(); } } public void setAlpha(float alpha) { if (AnimatorProxy.NEEDS_PROXY) { mProxy.setAlpha(alpha); } else { super.setAlpha(alpha); } } public float getTranslationY() { if (AnimatorProxy.NEEDS_PROXY) { return mProxy.getTranslationY(); } else { return super.getTranslationY(); } } public void setTranslationY(float translationY) { if (AnimatorProxy.NEEDS_PROXY) { mProxy.setTranslationY(translationY); } else { super.setTranslationY(translationY); } } }
1162584980-google-io
libprojects/abs/src/com/actionbarsherlock/internal/nineoldandroids/widget/NineFrameLayout.java
Java
asf20
1,999
package com.actionbarsherlock.internal.nineoldandroids.widget; import android.content.Context; import android.widget.HorizontalScrollView; import com.actionbarsherlock.internal.nineoldandroids.view.animation.AnimatorProxy; public class NineHorizontalScrollView extends HorizontalScrollView { private final AnimatorProxy mProxy; public NineHorizontalScrollView(Context context) { super(context); mProxy = AnimatorProxy.NEEDS_PROXY ? AnimatorProxy.wrap(this) : null; } @Override public void setVisibility(int visibility) { if (mProxy != null) { if (visibility == GONE) { clearAnimation(); } else if (visibility == VISIBLE) { setAnimation(mProxy); } } super.setVisibility(visibility); } public float getAlpha() { if (AnimatorProxy.NEEDS_PROXY) { return mProxy.getAlpha(); } else { return super.getAlpha(); } } public void setAlpha(float alpha) { if (AnimatorProxy.NEEDS_PROXY) { mProxy.setAlpha(alpha); } else { super.setAlpha(alpha); } } }
1162584980-google-io
libprojects/abs/src/com/actionbarsherlock/internal/nineoldandroids/widget/NineHorizontalScrollView.java
Java
asf20
1,187
package com.actionbarsherlock.internal.nineoldandroids.widget; import android.content.Context; import android.util.AttributeSet; import android.widget.LinearLayout; import com.actionbarsherlock.internal.nineoldandroids.view.animation.AnimatorProxy; public class NineLinearLayout extends LinearLayout { private final AnimatorProxy mProxy; public NineLinearLayout(Context context) { super(context); mProxy = AnimatorProxy.NEEDS_PROXY ? AnimatorProxy.wrap(this) : null; } public NineLinearLayout(Context context, AttributeSet attrs) { super(context, attrs); mProxy = AnimatorProxy.NEEDS_PROXY ? AnimatorProxy.wrap(this) : null; } public NineLinearLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mProxy = AnimatorProxy.NEEDS_PROXY ? AnimatorProxy.wrap(this) : null; } @Override public void setVisibility(int visibility) { if (mProxy != null) { if (visibility == GONE) { clearAnimation(); } else if (visibility == VISIBLE) { setAnimation(mProxy); } } super.setVisibility(visibility); } public float getAlpha() { if (AnimatorProxy.NEEDS_PROXY) { return mProxy.getAlpha(); } else { return super.getAlpha(); } } public void setAlpha(float alpha) { if (AnimatorProxy.NEEDS_PROXY) { mProxy.setAlpha(alpha); } else { super.setAlpha(alpha); } } public float getTranslationX() { if (AnimatorProxy.NEEDS_PROXY) { return mProxy.getTranslationX(); } else { return super.getTranslationX(); } } public void setTranslationX(float translationX) { if (AnimatorProxy.NEEDS_PROXY) { mProxy.setTranslationX(translationX); } else { super.setTranslationX(translationX); } } }
1162584980-google-io
libprojects/abs/src/com/actionbarsherlock/internal/nineoldandroids/widget/NineLinearLayout.java
Java
asf20
2,005
package com.actionbarsherlock.internal; import com.actionbarsherlock.ActionBarSherlock; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.internal.app.ActionBarWrapper; import com.actionbarsherlock.internal.view.menu.MenuWrapper; import com.actionbarsherlock.view.ActionMode; import com.actionbarsherlock.view.MenuInflater; import android.app.Activity; import android.content.Context; import android.util.Log; import android.util.TypedValue; import android.view.ContextThemeWrapper; import android.view.View; import android.view.Window; import android.view.ViewGroup.LayoutParams; @ActionBarSherlock.Implementation(api = 14) public class ActionBarSherlockNative extends ActionBarSherlock { private ActionBarWrapper mActionBar; private ActionModeWrapper mActionMode; private MenuWrapper mMenu; public ActionBarSherlockNative(Activity activity, int flags) { super(activity, flags); } @Override public ActionBar getActionBar() { if (DEBUG) Log.d(TAG, "[getActionBar]"); initActionBar(); return mActionBar; } private void initActionBar() { if (mActionBar != null || mActivity.getActionBar() == null) { return; } mActionBar = new ActionBarWrapper(mActivity); } @Override public void dispatchInvalidateOptionsMenu() { if (DEBUG) Log.d(TAG, "[dispatchInvalidateOptionsMenu]"); mActivity.getWindow().invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL); } @Override public boolean dispatchCreateOptionsMenu(android.view.Menu menu) { if (DEBUG) Log.d(TAG, "[dispatchCreateOptionsMenu] menu: " + menu); if (mMenu == null || menu != mMenu.unwrap()) { mMenu = new MenuWrapper(menu); } final boolean result = callbackCreateOptionsMenu(mMenu); if (DEBUG) Log.d(TAG, "[dispatchCreateOptionsMenu] returning " + result); return result; } @Override public boolean dispatchPrepareOptionsMenu(android.view.Menu menu) { if (DEBUG) Log.d(TAG, "[dispatchPrepareOptionsMenu] menu: " + menu); final boolean result = callbackPrepareOptionsMenu(mMenu); if (DEBUG) Log.d(TAG, "[dispatchPrepareOptionsMenu] returning " + result); return result; } @Override public boolean dispatchOptionsItemSelected(android.view.MenuItem item) { if (DEBUG) Log.d(TAG, "[dispatchOptionsItemSelected] item: " + item.getTitleCondensed()); final boolean result = callbackOptionsItemSelected(mMenu.findItem(item)); if (DEBUG) Log.d(TAG, "[dispatchOptionsItemSelected] returning " + result); return result; } @Override public boolean hasFeature(int feature) { if (DEBUG) Log.d(TAG, "[hasFeature] feature: " + feature); final boolean result = mActivity.getWindow().hasFeature(feature); if (DEBUG) Log.d(TAG, "[hasFeature] returning " + result); return result; } @Override public boolean requestFeature(int featureId) { if (DEBUG) Log.d(TAG, "[requestFeature] featureId: " + featureId); final boolean result = mActivity.getWindow().requestFeature(featureId); if (DEBUG) Log.d(TAG, "[requestFeature] returning " + result); return result; } @Override public void setUiOptions(int uiOptions) { if (DEBUG) Log.d(TAG, "[setUiOptions] uiOptions: " + uiOptions); mActivity.getWindow().setUiOptions(uiOptions); } @Override public void setUiOptions(int uiOptions, int mask) { if (DEBUG) Log.d(TAG, "[setUiOptions] uiOptions: " + uiOptions + ", mask: " + mask); mActivity.getWindow().setUiOptions(uiOptions, mask); } @Override public void setContentView(int layoutResId) { if (DEBUG) Log.d(TAG, "[setContentView] layoutResId: " + layoutResId); mActivity.getWindow().setContentView(layoutResId); initActionBar(); } @Override public void setContentView(View view, LayoutParams params) { if (DEBUG) Log.d(TAG, "[setContentView] view: " + view + ", params: " + params); mActivity.getWindow().setContentView(view, params); initActionBar(); } @Override public void addContentView(View view, LayoutParams params) { if (DEBUG) Log.d(TAG, "[addContentView] view: " + view + ", params: " + params); mActivity.getWindow().addContentView(view, params); initActionBar(); } @Override public void setTitle(CharSequence title) { if (DEBUG) Log.d(TAG, "[setTitle] title: " + title); mActivity.getWindow().setTitle(title); } @Override public void setProgressBarVisibility(boolean visible) { if (DEBUG) Log.d(TAG, "[setProgressBarVisibility] visible: " + visible); mActivity.setProgressBarVisibility(visible); } @Override public void setProgressBarIndeterminateVisibility(boolean visible) { if (DEBUG) Log.d(TAG, "[setProgressBarIndeterminateVisibility] visible: " + visible); mActivity.setProgressBarIndeterminateVisibility(visible); } @Override public void setProgressBarIndeterminate(boolean indeterminate) { if (DEBUG) Log.d(TAG, "[setProgressBarIndeterminate] indeterminate: " + indeterminate); mActivity.setProgressBarIndeterminate(indeterminate); } @Override public void setProgress(int progress) { if (DEBUG) Log.d(TAG, "[setProgress] progress: " + progress); mActivity.setProgress(progress); } @Override public void setSecondaryProgress(int secondaryProgress) { if (DEBUG) Log.d(TAG, "[setSecondaryProgress] secondaryProgress: " + secondaryProgress); mActivity.setSecondaryProgress(secondaryProgress); } @Override protected Context getThemedContext() { Context context = mActivity; TypedValue outValue = new TypedValue(); mActivity.getTheme().resolveAttribute(android.R.attr.actionBarWidgetTheme, outValue, true); if (outValue.resourceId != 0) { //We are unable to test if this is the same as our current theme //so we just wrap it and hope that if the attribute was specified //then the user is intentionally specifying an alternate theme. context = new ContextThemeWrapper(context, outValue.resourceId); } return context; } @Override public ActionMode startActionMode(com.actionbarsherlock.view.ActionMode.Callback callback) { if (DEBUG) Log.d(TAG, "[startActionMode] callback: " + callback); if (mActionMode != null) { mActionMode.finish(); } ActionModeCallbackWrapper wrapped = null; if (callback != null) { wrapped = new ActionModeCallbackWrapper(callback); } //Calling this will trigger the callback wrapper's onCreate which //is where we will set the new instance to mActionMode since we need //to pass it through to the sherlock callbacks and the call below //will not have returned yet to store its value. mActivity.startActionMode(wrapped); return mActionMode; } private class ActionModeCallbackWrapper implements android.view.ActionMode.Callback { private final ActionMode.Callback mCallback; public ActionModeCallbackWrapper(ActionMode.Callback callback) { mCallback = callback; } @Override public boolean onCreateActionMode(android.view.ActionMode mode, android.view.Menu menu) { //See ActionBarSherlockNative#startActionMode mActionMode = new ActionModeWrapper(mode); return mCallback.onCreateActionMode(mActionMode, mActionMode.getMenu()); } @Override public boolean onPrepareActionMode(android.view.ActionMode mode, android.view.Menu menu) { return mCallback.onPrepareActionMode(mActionMode, mActionMode.getMenu()); } @Override public boolean onActionItemClicked(android.view.ActionMode mode, android.view.MenuItem item) { return mCallback.onActionItemClicked(mActionMode, mActionMode.getMenu().findItem(item)); } @Override public void onDestroyActionMode(android.view.ActionMode mode) { mCallback.onDestroyActionMode(mActionMode); } } private class ActionModeWrapper extends ActionMode { private final android.view.ActionMode mActionMode; private MenuWrapper mMenu = null; ActionModeWrapper(android.view.ActionMode actionMode) { mActionMode = actionMode; } @Override public void setTitle(CharSequence title) { mActionMode.setTitle(title); } @Override public void setTitle(int resId) { mActionMode.setTitle(resId); } @Override public void setSubtitle(CharSequence subtitle) { mActionMode.setSubtitle(subtitle); } @Override public void setSubtitle(int resId) { mActionMode.setSubtitle(resId); } @Override public void setCustomView(View view) { mActionMode.setCustomView(view); } @Override public void invalidate() { mActionMode.invalidate(); } @Override public void finish() { mActionMode.finish(); } @Override public MenuWrapper getMenu() { if (mMenu == null) { mMenu = new MenuWrapper(mActionMode.getMenu()); } return mMenu; } @Override public CharSequence getTitle() { return mActionMode.getTitle(); } @Override public CharSequence getSubtitle() { return mActionMode.getSubtitle(); } @Override public View getCustomView() { return mActionMode.getCustomView(); } @Override public MenuInflater getMenuInflater() { return ActionBarSherlockNative.this.getMenuInflater(); } @Override public void setTag(Object tag) { mActionMode.setTag(tag); } @Override public Object getTag() { return mActionMode.getTag(); } } }
1162584980-google-io
libprojects/abs/src/com/actionbarsherlock/internal/ActionBarSherlockNative.java
Java
asf20
10,409
package com.actionbarsherlock.internal; import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; import static com.actionbarsherlock.internal.ResourcesCompat.getResources_getBoolean; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.xmlpull.v1.XmlPullParser; import android.app.Activity; import android.content.Context; import android.content.pm.ActivityInfo; import android.content.res.AssetManager; import android.content.res.Configuration; import android.content.res.Resources; import android.content.res.TypedArray; import android.content.res.XmlResourceParser; import android.os.Bundle; import android.util.AndroidRuntimeException; import android.util.Log; import android.util.TypedValue; import android.view.ContextThemeWrapper; import android.view.KeyCharacterMap; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewStub; import android.view.Window; import android.view.accessibility.AccessibilityEvent; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.FrameLayout; import android.widget.TextView; import com.actionbarsherlock.ActionBarSherlock; import com.actionbarsherlock.R; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.internal.app.ActionBarImpl; import com.actionbarsherlock.internal.view.StandaloneActionMode; import com.actionbarsherlock.internal.view.menu.ActionMenuPresenter; import com.actionbarsherlock.internal.view.menu.MenuBuilder; import com.actionbarsherlock.internal.view.menu.MenuItemImpl; import com.actionbarsherlock.internal.view.menu.MenuPresenter; import com.actionbarsherlock.internal.widget.ActionBarContainer; import com.actionbarsherlock.internal.widget.ActionBarContextView; import com.actionbarsherlock.internal.widget.ActionBarView; import com.actionbarsherlock.internal.widget.IcsProgressBar; import com.actionbarsherlock.view.ActionMode; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; @ActionBarSherlock.Implementation(api = 7) public class ActionBarSherlockCompat extends ActionBarSherlock implements MenuBuilder.Callback, com.actionbarsherlock.view.Window.Callback, MenuPresenter.Callback, android.view.MenuItem.OnMenuItemClickListener { /** Window features which are enabled by default. */ protected static final int DEFAULT_FEATURES = 0; public ActionBarSherlockCompat(Activity activity, int flags) { super(activity, flags); } /////////////////////////////////////////////////////////////////////////// // Properties /////////////////////////////////////////////////////////////////////////// /** Whether or not the device has a dedicated menu key button. */ private boolean mReserveOverflow; /** Lazy-load indicator for {@link #mReserveOverflow}. */ private boolean mReserveOverflowSet = false; /** Current menu instance for managing action items. */ private MenuBuilder mMenu; /** Map between native options items and sherlock items. */ protected HashMap<android.view.MenuItem, MenuItemImpl> mNativeItemMap; /** Indication of a long-press on the hardware menu key. */ private boolean mMenuKeyIsLongPress = false; /** Parent view of the window decoration (action bar, mode, etc.). */ private ViewGroup mDecor; /** Parent view of the activity content. */ private ViewGroup mContentParent; /** Whether or not the title is stable and can be displayed. */ private boolean mIsTitleReady = false; /** Whether or not the parent activity has been destroyed. */ private boolean mIsDestroyed = false; /* Emulate PanelFeatureState */ private boolean mClosingActionMenu; private boolean mMenuIsPrepared; private boolean mMenuRefreshContent; private Bundle mMenuFrozenActionViewState; /** Implementation which backs the action bar interface API. */ private ActionBarImpl aActionBar; /** Main action bar view which displays the core content. */ private ActionBarView wActionBar; /** Relevant window and action bar features flags. */ private int mFeatures = DEFAULT_FEATURES; /** Relevant user interface option flags. */ private int mUiOptions = 0; /** Decor indeterminate progress indicator. */ private IcsProgressBar mCircularProgressBar; /** Decor progress indicator. */ private IcsProgressBar mHorizontalProgressBar; /** Current displayed context action bar, if any. */ private ActionMode mActionMode; /** Parent view in which the context action bar is displayed. */ private ActionBarContextView mActionModeView; /** Title view used with dialogs. */ private TextView mTitleView; /** Current activity title. */ private CharSequence mTitle = null; /** Whether or not this "activity" is floating (i.e., a dialog) */ private boolean mIsFloating; /////////////////////////////////////////////////////////////////////////// // Instance methods /////////////////////////////////////////////////////////////////////////// @Override public ActionBar getActionBar() { if (DEBUG) Log.d(TAG, "[getActionBar]"); initActionBar(); return aActionBar; } private void initActionBar() { if (DEBUG) Log.d(TAG, "[initActionBar]"); // Initializing the window decor can change window feature flags. // Make sure that we have the correct set before performing the test below. if (mDecor == null) { installDecor(); } if ((aActionBar != null) || !hasFeature(Window.FEATURE_ACTION_BAR) || hasFeature(Window.FEATURE_NO_TITLE) || mActivity.isChild()) { return; } aActionBar = new ActionBarImpl(mActivity, mFeatures); if (!mIsDelegate) { //We may never get another chance to set the title wActionBar.setWindowTitle(mActivity.getTitle()); } } @Override protected Context getThemedContext() { return aActionBar.getThemedContext(); } @Override public void setTitle(CharSequence title) { if (DEBUG) Log.d(TAG, "[setTitle] title: " + title); dispatchTitleChanged(title, 0); } @Override public ActionMode startActionMode(ActionMode.Callback callback) { if (DEBUG) Log.d(TAG, "[startActionMode] callback: " + callback); if (mActionMode != null) { mActionMode.finish(); } final ActionMode.Callback wrappedCallback = new ActionModeCallbackWrapper(callback); ActionMode mode = null; //Emulate Activity's onWindowStartingActionMode: initActionBar(); if (aActionBar != null) { mode = aActionBar.startActionMode(wrappedCallback); } if (mode != null) { mActionMode = mode; } else { if (mActionModeView == null) { ViewStub stub = (ViewStub)mDecor.findViewById(R.id.abs__action_mode_bar_stub); if (stub != null) { mActionModeView = (ActionBarContextView)stub.inflate(); } } if (mActionModeView != null) { mActionModeView.killMode(); mode = new StandaloneActionMode(mActivity, mActionModeView, wrappedCallback, true); if (callback.onCreateActionMode(mode, mode.getMenu())) { mode.invalidate(); mActionModeView.initForMode(mode); mActionModeView.setVisibility(View.VISIBLE); mActionMode = mode; mActionModeView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); } else { mActionMode = null; } } } if (mActionMode != null && mActivity instanceof OnActionModeStartedListener) { ((OnActionModeStartedListener)mActivity).onActionModeStarted(mActionMode); } return mActionMode; } /////////////////////////////////////////////////////////////////////////// // Lifecycle and interaction callbacks for delegation /////////////////////////////////////////////////////////////////////////// @Override public void dispatchConfigurationChanged(Configuration newConfig) { if (DEBUG) Log.d(TAG, "[dispatchConfigurationChanged] newConfig: " + newConfig); if (aActionBar != null) { aActionBar.onConfigurationChanged(newConfig); } } @Override public void dispatchPostResume() { if (DEBUG) Log.d(TAG, "[dispatchPostResume]"); if (aActionBar != null) { aActionBar.setShowHideAnimationEnabled(true); } } @Override public void dispatchPause() { if (DEBUG) Log.d(TAG, "[dispatchPause]"); if (wActionBar != null && wActionBar.isOverflowMenuShowing()) { wActionBar.hideOverflowMenu(); } } @Override public void dispatchStop() { if (DEBUG) Log.d(TAG, "[dispatchStop]"); if (aActionBar != null) { aActionBar.setShowHideAnimationEnabled(false); } } @Override public void dispatchInvalidateOptionsMenu() { if (DEBUG) Log.d(TAG, "[dispatchInvalidateOptionsMenu]"); Bundle savedActionViewStates = null; if (mMenu != null) { savedActionViewStates = new Bundle(); mMenu.saveActionViewStates(savedActionViewStates); if (savedActionViewStates.size() > 0) { mMenuFrozenActionViewState = savedActionViewStates; } // This will be started again when the panel is prepared. mMenu.stopDispatchingItemsChanged(); mMenu.clear(); } mMenuRefreshContent = true; // Prepare the options panel if we have an action bar if (wActionBar != null) { mMenuIsPrepared = false; preparePanel(); } } @Override public boolean dispatchOpenOptionsMenu() { if (DEBUG) Log.d(TAG, "[dispatchOpenOptionsMenu]"); if (!isReservingOverflow()) { return false; } return wActionBar.showOverflowMenu(); } @Override public boolean dispatchCloseOptionsMenu() { if (DEBUG) Log.d(TAG, "[dispatchCloseOptionsMenu]"); if (!isReservingOverflow()) { return false; } return wActionBar.hideOverflowMenu(); } @Override public void dispatchPostCreate(Bundle savedInstanceState) { if (DEBUG) Log.d(TAG, "[dispatchOnPostCreate]"); if (mIsDelegate) { mIsTitleReady = true; } if (mDecor == null) { initActionBar(); } } @Override public boolean dispatchCreateOptionsMenu(android.view.Menu menu) { if (DEBUG) { Log.d(TAG, "[dispatchCreateOptionsMenu] android.view.Menu: " + menu); Log.d(TAG, "[dispatchCreateOptionsMenu] returning true"); } return true; } @Override public boolean dispatchPrepareOptionsMenu(android.view.Menu menu) { if (DEBUG) Log.d(TAG, "[dispatchPrepareOptionsMenu] android.view.Menu: " + menu); if (mActionMode != null) { return false; } mMenuIsPrepared = false; if (!preparePanel()) { return false; } if (isReservingOverflow()) { return false; } if (mNativeItemMap == null) { mNativeItemMap = new HashMap<android.view.MenuItem, MenuItemImpl>(); } else { mNativeItemMap.clear(); } if (mMenu == null) { return false; } boolean result = mMenu.bindNativeOverflow(menu, this, mNativeItemMap); if (DEBUG) Log.d(TAG, "[dispatchPrepareOptionsMenu] returning " + result); return result; } @Override public boolean dispatchOptionsItemSelected(android.view.MenuItem item) { throw new IllegalStateException("Native callback invoked. Create a test case and report!"); } @Override public boolean dispatchMenuOpened(int featureId, android.view.Menu menu) { if (DEBUG) Log.d(TAG, "[dispatchMenuOpened] featureId: " + featureId + ", menu: " + menu); if (featureId == Window.FEATURE_ACTION_BAR || featureId == Window.FEATURE_OPTIONS_PANEL) { if (aActionBar != null) { aActionBar.dispatchMenuVisibilityChanged(true); } return true; } return false; } @Override public void dispatchPanelClosed(int featureId, android.view.Menu menu){ if (DEBUG) Log.d(TAG, "[dispatchPanelClosed] featureId: " + featureId + ", menu: " + menu); if (featureId == Window.FEATURE_ACTION_BAR || featureId == Window.FEATURE_OPTIONS_PANEL) { if (aActionBar != null) { aActionBar.dispatchMenuVisibilityChanged(false); } } } @Override public void dispatchTitleChanged(CharSequence title, int color) { if (DEBUG) Log.d(TAG, "[dispatchTitleChanged] title: " + title + ", color: " + color); if (!mIsDelegate || mIsTitleReady) { if (mTitleView != null) { mTitleView.setText(title); } else if (wActionBar != null) { wActionBar.setWindowTitle(title); } } mTitle = title; } @Override public boolean dispatchKeyEvent(KeyEvent event) { if (DEBUG) Log.d(TAG, "[dispatchKeyEvent] event: " + event); final int keyCode = event.getKeyCode(); // Not handled by the view hierarchy, does the action bar want it // to cancel out of something special? if (keyCode == KeyEvent.KEYCODE_BACK) { final int action = event.getAction(); // Back cancels action modes first. if (mActionMode != null) { if (action == KeyEvent.ACTION_UP) { mActionMode.finish(); } if (DEBUG) Log.d(TAG, "[dispatchKeyEvent] returning true"); return true; } // Next collapse any expanded action views. if (wActionBar != null && wActionBar.hasExpandedActionView()) { if (action == KeyEvent.ACTION_UP) { wActionBar.collapseActionView(); } if (DEBUG) Log.d(TAG, "[dispatchKeyEvent] returning true"); return true; } } boolean result = false; if (keyCode == KeyEvent.KEYCODE_MENU && isReservingOverflow()) { if (event.getAction() == KeyEvent.ACTION_DOWN && event.isLongPress()) { mMenuKeyIsLongPress = true; } else if (event.getAction() == KeyEvent.ACTION_UP) { if (!mMenuKeyIsLongPress) { if (mActionMode == null && wActionBar != null) { if (wActionBar.isOverflowMenuShowing()) { wActionBar.hideOverflowMenu(); } else { wActionBar.showOverflowMenu(); } } result = true; } mMenuKeyIsLongPress = false; } } if (DEBUG) Log.d(TAG, "[dispatchKeyEvent] returning " + result); return result; } @Override public void dispatchDestroy() { mIsDestroyed = true; } /////////////////////////////////////////////////////////////////////////// // Menu callback lifecycle and creation /////////////////////////////////////////////////////////////////////////// private boolean preparePanel() { // Already prepared (isPrepared will be reset to false later) if (mMenuIsPrepared) { return true; } // Init the panel state's menu--return false if init failed if (mMenu == null || mMenuRefreshContent) { if (mMenu == null) { if (!initializePanelMenu() || (mMenu == null)) { return false; } } if (wActionBar != null) { wActionBar.setMenu(mMenu, this); } // Call callback, and return if it doesn't want to display menu. // Creating the panel menu will involve a lot of manipulation; // don't dispatch change events to presenters until we're done. mMenu.stopDispatchingItemsChanged(); if (!callbackCreateOptionsMenu(mMenu)) { // Ditch the menu created above mMenu = null; if (wActionBar != null) { // Don't show it in the action bar either wActionBar.setMenu(null, this); } return false; } mMenuRefreshContent = false; } // Callback and return if the callback does not want to show the menu // Preparing the panel menu can involve a lot of manipulation; // don't dispatch change events to presenters until we're done. mMenu.stopDispatchingItemsChanged(); // Restore action view state before we prepare. This gives apps // an opportunity to override frozen/restored state in onPrepare. if (mMenuFrozenActionViewState != null) { mMenu.restoreActionViewStates(mMenuFrozenActionViewState); mMenuFrozenActionViewState = null; } if (!callbackPrepareOptionsMenu(mMenu)) { if (wActionBar != null) { // The app didn't want to show the menu for now but it still exists. // Clear it out of the action bar. wActionBar.setMenu(null, this); } mMenu.startDispatchingItemsChanged(); return false; } // Set the proper keymap KeyCharacterMap kmap = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD); mMenu.setQwertyMode(kmap.getKeyboardType() != KeyCharacterMap.NUMERIC); mMenu.startDispatchingItemsChanged(); // Set other state mMenuIsPrepared = true; return true; } public boolean onMenuItemSelected(MenuBuilder menu, MenuItem item) { return callbackOptionsItemSelected(item); } public void onMenuModeChange(MenuBuilder menu) { reopenMenu(true); } private void reopenMenu(boolean toggleMenuMode) { if (wActionBar != null && wActionBar.isOverflowReserved()) { if (!wActionBar.isOverflowMenuShowing() || !toggleMenuMode) { if (wActionBar.getVisibility() == View.VISIBLE) { if (callbackPrepareOptionsMenu(mMenu)) { wActionBar.showOverflowMenu(); } } } else { wActionBar.hideOverflowMenu(); } return; } } private boolean initializePanelMenu() { Context context = mActivity;//getContext(); // If we have an action bar, initialize the menu with a context themed for it. if (wActionBar != null) { TypedValue outValue = new TypedValue(); Resources.Theme currentTheme = context.getTheme(); currentTheme.resolveAttribute(R.attr.actionBarWidgetTheme, outValue, true); final int targetThemeRes = outValue.resourceId; if (targetThemeRes != 0 /*&& context.getThemeResId() != targetThemeRes*/) { context = new ContextThemeWrapper(context, targetThemeRes); } } mMenu = new MenuBuilder(context); mMenu.setCallback(this); return true; } void checkCloseActionMenu(Menu menu) { if (mClosingActionMenu) { return; } mClosingActionMenu = true; wActionBar.dismissPopupMenus(); //Callback cb = getCallback(); //if (cb != null && !isDestroyed()) { // cb.onPanelClosed(FEATURE_ACTION_BAR, menu); //} mClosingActionMenu = false; } @Override public boolean onOpenSubMenu(MenuBuilder subMenu) { return true; } @Override public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) { checkCloseActionMenu(menu); } @Override public boolean onMenuItemClick(android.view.MenuItem item) { if (DEBUG) Log.d(TAG, "[mNativeItemListener.onMenuItemClick] item: " + item); final MenuItemImpl sherlockItem = mNativeItemMap.get(item); if (sherlockItem != null) { sherlockItem.invoke(); } else { Log.e(TAG, "Options item \"" + item + "\" not found in mapping"); } return true; //Do not allow continuation of native handling } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { return callbackOptionsItemSelected(item); } /////////////////////////////////////////////////////////////////////////// // Progress bar interaction and internal handling /////////////////////////////////////////////////////////////////////////// @Override public void setProgressBarVisibility(boolean visible) { if (DEBUG) Log.d(TAG, "[setProgressBarVisibility] visible: " + visible); setFeatureInt(Window.FEATURE_PROGRESS, visible ? Window.PROGRESS_VISIBILITY_ON : Window.PROGRESS_VISIBILITY_OFF); } @Override public void setProgressBarIndeterminateVisibility(boolean visible) { if (DEBUG) Log.d(TAG, "[setProgressBarIndeterminateVisibility] visible: " + visible); setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS, visible ? Window.PROGRESS_VISIBILITY_ON : Window.PROGRESS_VISIBILITY_OFF); } @Override public void setProgressBarIndeterminate(boolean indeterminate) { if (DEBUG) Log.d(TAG, "[setProgressBarIndeterminate] indeterminate: " + indeterminate); setFeatureInt(Window.FEATURE_PROGRESS, indeterminate ? Window.PROGRESS_INDETERMINATE_ON : Window.PROGRESS_INDETERMINATE_OFF); } @Override public void setProgress(int progress) { if (DEBUG) Log.d(TAG, "[setProgress] progress: " + progress); setFeatureInt(Window.FEATURE_PROGRESS, progress + Window.PROGRESS_START); } @Override public void setSecondaryProgress(int secondaryProgress) { if (DEBUG) Log.d(TAG, "[setSecondaryProgress] secondaryProgress: " + secondaryProgress); setFeatureInt(Window.FEATURE_PROGRESS, secondaryProgress + Window.PROGRESS_SECONDARY_START); } private void setFeatureInt(int featureId, int value) { updateInt(featureId, value, false); } private void updateInt(int featureId, int value, boolean fromResume) { // Do nothing if the decor is not yet installed... an update will // need to be forced when we eventually become active. if (mContentParent == null) { return; } final int featureMask = 1 << featureId; if ((getFeatures() & featureMask) == 0 && !fromResume) { return; } onIntChanged(featureId, value); } private void onIntChanged(int featureId, int value) { if (featureId == Window.FEATURE_PROGRESS || featureId == Window.FEATURE_INDETERMINATE_PROGRESS) { updateProgressBars(value); } } private void updateProgressBars(int value) { IcsProgressBar circularProgressBar = getCircularProgressBar(true); IcsProgressBar horizontalProgressBar = getHorizontalProgressBar(true); final int features = mFeatures;//getLocalFeatures(); if (value == Window.PROGRESS_VISIBILITY_ON) { if ((features & (1 << Window.FEATURE_PROGRESS)) != 0) { int level = horizontalProgressBar.getProgress(); int visibility = (horizontalProgressBar.isIndeterminate() || level < 10000) ? View.VISIBLE : View.INVISIBLE; horizontalProgressBar.setVisibility(visibility); } if ((features & (1 << Window.FEATURE_INDETERMINATE_PROGRESS)) != 0) { circularProgressBar.setVisibility(View.VISIBLE); } } else if (value == Window.PROGRESS_VISIBILITY_OFF) { if ((features & (1 << Window.FEATURE_PROGRESS)) != 0) { horizontalProgressBar.setVisibility(View.GONE); } if ((features & (1 << Window.FEATURE_INDETERMINATE_PROGRESS)) != 0) { circularProgressBar.setVisibility(View.GONE); } } else if (value == Window.PROGRESS_INDETERMINATE_ON) { horizontalProgressBar.setIndeterminate(true); } else if (value == Window.PROGRESS_INDETERMINATE_OFF) { horizontalProgressBar.setIndeterminate(false); } else if (Window.PROGRESS_START <= value && value <= Window.PROGRESS_END) { // We want to set the progress value before testing for visibility // so that when the progress bar becomes visible again, it has the // correct level. horizontalProgressBar.setProgress(value - Window.PROGRESS_START); if (value < Window.PROGRESS_END) { showProgressBars(horizontalProgressBar, circularProgressBar); } else { hideProgressBars(horizontalProgressBar, circularProgressBar); } } else if (Window.PROGRESS_SECONDARY_START <= value && value <= Window.PROGRESS_SECONDARY_END) { horizontalProgressBar.setSecondaryProgress(value - Window.PROGRESS_SECONDARY_START); showProgressBars(horizontalProgressBar, circularProgressBar); } } private void showProgressBars(IcsProgressBar horizontalProgressBar, IcsProgressBar spinnyProgressBar) { final int features = mFeatures;//getLocalFeatures(); if ((features & (1 << Window.FEATURE_INDETERMINATE_PROGRESS)) != 0 && spinnyProgressBar.getVisibility() == View.INVISIBLE) { spinnyProgressBar.setVisibility(View.VISIBLE); } // Only show the progress bars if the primary progress is not complete if ((features & (1 << Window.FEATURE_PROGRESS)) != 0 && horizontalProgressBar.getProgress() < 10000) { horizontalProgressBar.setVisibility(View.VISIBLE); } } private void hideProgressBars(IcsProgressBar horizontalProgressBar, IcsProgressBar spinnyProgressBar) { final int features = mFeatures;//getLocalFeatures(); Animation anim = AnimationUtils.loadAnimation(mActivity, android.R.anim.fade_out); anim.setDuration(1000); if ((features & (1 << Window.FEATURE_INDETERMINATE_PROGRESS)) != 0 && spinnyProgressBar.getVisibility() == View.VISIBLE) { spinnyProgressBar.startAnimation(anim); spinnyProgressBar.setVisibility(View.INVISIBLE); } if ((features & (1 << Window.FEATURE_PROGRESS)) != 0 && horizontalProgressBar.getVisibility() == View.VISIBLE) { horizontalProgressBar.startAnimation(anim); horizontalProgressBar.setVisibility(View.INVISIBLE); } } private IcsProgressBar getCircularProgressBar(boolean shouldInstallDecor) { if (mCircularProgressBar != null) { return mCircularProgressBar; } if (mContentParent == null && shouldInstallDecor) { installDecor(); } mCircularProgressBar = (IcsProgressBar)mDecor.findViewById(R.id.abs__progress_circular); if (mCircularProgressBar != null) { mCircularProgressBar.setVisibility(View.INVISIBLE); } return mCircularProgressBar; } private IcsProgressBar getHorizontalProgressBar(boolean shouldInstallDecor) { if (mHorizontalProgressBar != null) { return mHorizontalProgressBar; } if (mContentParent == null && shouldInstallDecor) { installDecor(); } mHorizontalProgressBar = (IcsProgressBar)mDecor.findViewById(R.id.abs__progress_horizontal); if (mHorizontalProgressBar != null) { mHorizontalProgressBar.setVisibility(View.INVISIBLE); } return mHorizontalProgressBar; } /////////////////////////////////////////////////////////////////////////// // Feature management and content interaction and creation /////////////////////////////////////////////////////////////////////////// private int getFeatures() { if (DEBUG) Log.d(TAG, "[getFeatures] returning " + mFeatures); return mFeatures; } @Override public boolean hasFeature(int featureId) { if (DEBUG) Log.d(TAG, "[hasFeature] featureId: " + featureId); boolean result = (mFeatures & (1 << featureId)) != 0; if (DEBUG) Log.d(TAG, "[hasFeature] returning " + result); return result; } @Override public boolean requestFeature(int featureId) { if (DEBUG) Log.d(TAG, "[requestFeature] featureId: " + featureId); if (mContentParent != null) { throw new AndroidRuntimeException("requestFeature() must be called before adding content"); } switch (featureId) { case Window.FEATURE_ACTION_BAR: case Window.FEATURE_ACTION_BAR_OVERLAY: case Window.FEATURE_ACTION_MODE_OVERLAY: case Window.FEATURE_INDETERMINATE_PROGRESS: case Window.FEATURE_NO_TITLE: case Window.FEATURE_PROGRESS: mFeatures |= (1 << featureId); return true; default: return false; } } @Override public void setUiOptions(int uiOptions) { if (DEBUG) Log.d(TAG, "[setUiOptions] uiOptions: " + uiOptions); mUiOptions = uiOptions; } @Override public void setUiOptions(int uiOptions, int mask) { if (DEBUG) Log.d(TAG, "[setUiOptions] uiOptions: " + uiOptions + ", mask: " + mask); mUiOptions = (mUiOptions & ~mask) | (uiOptions & mask); } @Override public void setContentView(int layoutResId) { if (DEBUG) Log.d(TAG, "[setContentView] layoutResId: " + layoutResId); if (mContentParent == null) { installDecor(); } else { mContentParent.removeAllViews(); } mActivity.getLayoutInflater().inflate(layoutResId, mContentParent); android.view.Window.Callback callback = mActivity.getWindow().getCallback(); if (callback != null) { callback.onContentChanged(); } initActionBar(); } @Override public void setContentView(View view, ViewGroup.LayoutParams params) { if (DEBUG) Log.d(TAG, "[setContentView] view: " + view + ", params: " + params); if (mContentParent == null) { installDecor(); } else { mContentParent.removeAllViews(); } mContentParent.addView(view, params); android.view.Window.Callback callback = mActivity.getWindow().getCallback(); if (callback != null) { callback.onContentChanged(); } initActionBar(); } @Override public void addContentView(View view, ViewGroup.LayoutParams params) { if (DEBUG) Log.d(TAG, "[addContentView] view: " + view + ", params: " + params); if (mContentParent == null) { installDecor(); } mContentParent.addView(view, params); initActionBar(); } private void installDecor() { if (DEBUG) Log.d(TAG, "[installDecor]"); if (mDecor == null) { mDecor = (ViewGroup)mActivity.getWindow().getDecorView().findViewById(android.R.id.content); } if (mContentParent == null) { //Since we are not operating at the window level we need to take //into account the fact that the true decor may have already been //initialized and had content attached to it. If that is the case, //copy over its children to our new content container. List<View> views = null; if (mDecor.getChildCount() > 0) { views = new ArrayList<View>(1); //Usually there's only one child for (int i = 0, children = mDecor.getChildCount(); i < children; i++) { View child = mDecor.getChildAt(0); mDecor.removeView(child); views.add(child); } } mContentParent = generateLayout(); //Copy over the old children. See above for explanation. if (views != null) { for (View child : views) { mContentParent.addView(child); } } mTitleView = (TextView)mDecor.findViewById(android.R.id.title); if (mTitleView != null) { if (hasFeature(Window.FEATURE_NO_TITLE)) { mTitleView.setVisibility(View.GONE); if (mContentParent instanceof FrameLayout) { ((FrameLayout)mContentParent).setForeground(null); } } else { mTitleView.setText(mTitle); } } else { wActionBar = (ActionBarView)mDecor.findViewById(R.id.abs__action_bar); if (wActionBar != null) { wActionBar.setWindowCallback(this); if (wActionBar.getTitle() == null) { wActionBar.setWindowTitle(mActivity.getTitle()); } if (hasFeature(Window.FEATURE_PROGRESS)) { wActionBar.initProgress(); } if (hasFeature(Window.FEATURE_INDETERMINATE_PROGRESS)) { wActionBar.initIndeterminateProgress(); } //Since we don't require onCreate dispatching, parse for uiOptions here int uiOptions = loadUiOptionsFromManifest(mActivity); if (uiOptions != 0) { mUiOptions = uiOptions; } boolean splitActionBar = false; final boolean splitWhenNarrow = (mUiOptions & ActivityInfo.UIOPTION_SPLIT_ACTION_BAR_WHEN_NARROW) != 0; if (splitWhenNarrow) { splitActionBar = getResources_getBoolean(mActivity, R.bool.abs__split_action_bar_is_narrow); } else { splitActionBar = mActivity.getTheme() .obtainStyledAttributes(R.styleable.SherlockTheme) .getBoolean(R.styleable.SherlockTheme_windowSplitActionBar, false); } final ActionBarContainer splitView = (ActionBarContainer)mDecor.findViewById(R.id.abs__split_action_bar); if (splitView != null) { wActionBar.setSplitView(splitView); wActionBar.setSplitActionBar(splitActionBar); wActionBar.setSplitWhenNarrow(splitWhenNarrow); mActionModeView = (ActionBarContextView)mDecor.findViewById(R.id.abs__action_context_bar); mActionModeView.setSplitView(splitView); mActionModeView.setSplitActionBar(splitActionBar); mActionModeView.setSplitWhenNarrow(splitWhenNarrow); } else if (splitActionBar) { Log.e(TAG, "Requested split action bar with incompatible window decor! Ignoring request."); } // Post the panel invalidate for later; avoid application onCreateOptionsMenu // being called in the middle of onCreate or similar. mDecor.post(new Runnable() { @Override public void run() { //Invalidate if the panel menu hasn't been created before this. if (!mIsDestroyed && !mActivity.isFinishing() && mMenu == null) { dispatchInvalidateOptionsMenu(); } } }); } } } } private ViewGroup generateLayout() { if (DEBUG) Log.d(TAG, "[generateLayout]"); // Apply data from current theme. TypedArray a = mActivity.getTheme().obtainStyledAttributes(R.styleable.SherlockTheme); mIsFloating = a.getBoolean(R.styleable.SherlockTheme_android_windowIsFloating, false); if (!a.hasValue(R.styleable.SherlockTheme_windowActionBar)) { throw new IllegalStateException("You must use Theme.Sherlock, Theme.Sherlock.Light, Theme.Sherlock.Light.DarkActionBar, or a derivative."); } if (a.getBoolean(R.styleable.SherlockTheme_windowNoTitle, false)) { requestFeature(Window.FEATURE_NO_TITLE); } else if (a.getBoolean(R.styleable.SherlockTheme_windowActionBar, false)) { // Don't allow an action bar if there is no title. requestFeature(Window.FEATURE_ACTION_BAR); } if (a.getBoolean(R.styleable.SherlockTheme_windowActionBarOverlay, false)) { requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY); } if (a.getBoolean(R.styleable.SherlockTheme_windowActionModeOverlay, false)) { requestFeature(Window.FEATURE_ACTION_MODE_OVERLAY); } a.recycle(); int layoutResource; if (!hasFeature(Window.FEATURE_NO_TITLE)) { if (mIsFloating) { //Trash original dialog LinearLayout mDecor = (ViewGroup)mDecor.getParent(); mDecor.removeAllViews(); layoutResource = R.layout.abs__dialog_title_holo; } else { if (hasFeature(Window.FEATURE_ACTION_BAR_OVERLAY)) { layoutResource = R.layout.abs__screen_action_bar_overlay; } else { layoutResource = R.layout.abs__screen_action_bar; } } } else if (hasFeature(Window.FEATURE_ACTION_MODE_OVERLAY) && !hasFeature(Window.FEATURE_NO_TITLE)) { layoutResource = R.layout.abs__screen_simple_overlay_action_mode; } else { layoutResource = R.layout.abs__screen_simple; } if (DEBUG) Log.d(TAG, "[generateLayout] using screen XML " + mActivity.getResources().getString(layoutResource)); View in = mActivity.getLayoutInflater().inflate(layoutResource, null); mDecor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT)); ViewGroup contentParent = (ViewGroup)mDecor.findViewById(R.id.abs__content); if (contentParent == null) { throw new RuntimeException("Couldn't find content container view"); } //Make our new child the true content view (for fragments). VERY VOLATILE! mDecor.setId(View.NO_ID); contentParent.setId(android.R.id.content); if (hasFeature(Window.FEATURE_INDETERMINATE_PROGRESS)) { IcsProgressBar progress = getCircularProgressBar(false); if (progress != null) { progress.setIndeterminate(true); } } return contentParent; } /////////////////////////////////////////////////////////////////////////// // Miscellaneous /////////////////////////////////////////////////////////////////////////// /** * Determine whether or not the device has a dedicated menu key. * * @return {@code true} if native menu key is present. */ private boolean isReservingOverflow() { if (!mReserveOverflowSet) { mReserveOverflow = ActionMenuPresenter.reserveOverflow(mActivity); mReserveOverflowSet = true; } return mReserveOverflow; } private static int loadUiOptionsFromManifest(Activity activity) { int uiOptions = 0; try { final String thisPackage = activity.getClass().getName(); if (DEBUG) Log.i(TAG, "Parsing AndroidManifest.xml for " + thisPackage); final String packageName = activity.getApplicationInfo().packageName; final AssetManager am = activity.createPackageContext(packageName, 0).getAssets(); final XmlResourceParser xml = am.openXmlResourceParser("AndroidManifest.xml"); int eventType = xml.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { String name = xml.getName(); if ("application".equals(name)) { //Check if the <application> has the attribute if (DEBUG) Log.d(TAG, "Got <application>"); for (int i = xml.getAttributeCount() - 1; i >= 0; i--) { if (DEBUG) Log.d(TAG, xml.getAttributeName(i) + ": " + xml.getAttributeValue(i)); if ("uiOptions".equals(xml.getAttributeName(i))) { uiOptions = xml.getAttributeIntValue(i, 0); break; //out of for loop } } } else if ("activity".equals(name)) { //Check if the <activity> is us and has the attribute if (DEBUG) Log.d(TAG, "Got <activity>"); Integer activityUiOptions = null; String activityPackage = null; boolean isOurActivity = false; for (int i = xml.getAttributeCount() - 1; i >= 0; i--) { if (DEBUG) Log.d(TAG, xml.getAttributeName(i) + ": " + xml.getAttributeValue(i)); //We need both uiOptions and name attributes String attrName = xml.getAttributeName(i); if ("uiOptions".equals(attrName)) { activityUiOptions = xml.getAttributeIntValue(i, 0); } else if ("name".equals(attrName)) { activityPackage = cleanActivityName(packageName, xml.getAttributeValue(i)); if (!thisPackage.equals(activityPackage)) { break; //out of for loop } isOurActivity = true; } //Make sure we have both attributes before processing if ((activityUiOptions != null) && (activityPackage != null)) { //Our activity, uiOptions specified, override with our value uiOptions = activityUiOptions.intValue(); } } if (isOurActivity) { //If we matched our activity but it had no logo don't //do any more processing of the manifest break; } } } eventType = xml.nextToken(); } } catch (Exception e) { e.printStackTrace(); } if (DEBUG) Log.i(TAG, "Returning " + Integer.toHexString(uiOptions)); return uiOptions; } public static String cleanActivityName(String manifestPackage, String activityName) { if (activityName.charAt(0) == '.') { //Relative activity name (e.g., android:name=".ui.SomeClass") return manifestPackage + activityName; } if (activityName.indexOf('.', 1) == -1) { //Unqualified activity name (e.g., android:name="SomeClass") return manifestPackage + "." + activityName; } //Fully-qualified activity name (e.g., "com.my.package.SomeClass") return activityName; } /** * Clears out internal reference when the action mode is destroyed. */ private class ActionModeCallbackWrapper implements ActionMode.Callback { private final ActionMode.Callback mWrapped; public ActionModeCallbackWrapper(ActionMode.Callback wrapped) { mWrapped = wrapped; } public boolean onCreateActionMode(ActionMode mode, Menu menu) { return mWrapped.onCreateActionMode(mode, menu); } public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return mWrapped.onPrepareActionMode(mode, menu); } public boolean onActionItemClicked(ActionMode mode, MenuItem item) { return mWrapped.onActionItemClicked(mode, item); } public void onDestroyActionMode(ActionMode mode) { mWrapped.onDestroyActionMode(mode); if (mActionModeView != null) { mActionModeView.setVisibility(View.GONE); mActionModeView.removeAllViews(); } if (mActivity instanceof OnActionModeFinishedListener) { ((OnActionModeFinishedListener)mActivity).onActionModeFinished(mActionMode); } mActionMode = null; } } }
1162584980-google-io
libprojects/abs/src/com/actionbarsherlock/internal/ActionBarSherlockCompat.java
Java
asf20
45,962
package com.actionbarsherlock.internal; import android.content.Context; import android.os.Build; import android.util.DisplayMetrics; import com.actionbarsherlock.R; public final class ResourcesCompat { //No instances private ResourcesCompat() {} /** * Support implementation of {@code getResources().getBoolean()} that we * can use to simulate filtering based on width and smallest width * qualifiers on pre-3.2. * * @param context Context to load booleans from on 3.2+ and to fetch the * display metrics. * @param id Id of boolean to load. * @return Associated boolean value as reflected by the current display * metrics. */ public static boolean getResources_getBoolean(Context context, int id) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { return context.getResources().getBoolean(id); } DisplayMetrics metrics = context.getResources().getDisplayMetrics(); float widthDp = metrics.widthPixels / metrics.density; float heightDp = metrics.heightPixels / metrics.density; float smallestWidthDp = (widthDp < heightDp) ? widthDp : heightDp; if (id == R.bool.abs__action_bar_embed_tabs) { if (widthDp >= 480) { return true; //values-w480dp } return false; //values } if (id == R.bool.abs__split_action_bar_is_narrow) { if (widthDp >= 480) { return false; //values-w480dp } return true; //values } if (id == R.bool.abs__action_bar_expanded_action_views_exclusive) { if (smallestWidthDp >= 600) { return false; //values-sw600dp } return true; //values } if (id == R.bool.abs__config_allowActionMenuItemTextWithIcon) { if (widthDp >= 480) { return true; //values-w480dp } return false; //values } throw new IllegalArgumentException("Unknown boolean resource ID " + id); } /** * Support implementation of {@code getResources().getInteger()} that we * can use to simulate filtering based on width qualifiers on pre-3.2. * * @param context Context to load integers from on 3.2+ and to fetch the * display metrics. * @param id Id of integer to load. * @return Associated integer value as reflected by the current display * metrics. */ public static int getResources_getInteger(Context context, int id) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { return context.getResources().getInteger(id); } DisplayMetrics metrics = context.getResources().getDisplayMetrics(); float widthDp = metrics.widthPixels / metrics.density; if (id == R.integer.abs__max_action_buttons) { if (widthDp >= 600) { return 5; //values-w600dp } if (widthDp >= 500) { return 4; //values-w500dp } if (widthDp >= 360) { return 3; //values-w360dp } return 2; //values } throw new IllegalArgumentException("Unknown integer resource ID " + id); } }
1162584980-google-io
libprojects/abs/src/com/actionbarsherlock/internal/ResourcesCompat.java
Java
asf20
3,327
package com.actionbarsherlock.internal.view; import com.actionbarsherlock.internal.view.menu.SubMenuWrapper; import com.actionbarsherlock.view.ActionProvider; import android.view.View; public class ActionProviderWrapper extends android.view.ActionProvider { private final ActionProvider mProvider; public ActionProviderWrapper(ActionProvider provider) { super(null/*TODO*/); //XXX this *should* be unused mProvider = provider; } public ActionProvider unwrap() { return mProvider; } @Override public View onCreateActionView() { return mProvider.onCreateActionView(); } @Override public boolean hasSubMenu() { return mProvider.hasSubMenu(); } @Override public boolean onPerformDefaultAction() { return mProvider.onPerformDefaultAction(); } @Override public void onPrepareSubMenu(android.view.SubMenu subMenu) { mProvider.onPrepareSubMenu(new SubMenuWrapper(subMenu)); } }
1162584980-google-io
libprojects/abs/src/com/actionbarsherlock/internal/view/ActionProviderWrapper.java
Java
asf20
1,004
package com.actionbarsherlock.internal.view; import android.view.View; public interface View_OnAttachStateChangeListener { void onViewAttachedToWindow(View v); void onViewDetachedFromWindow(View v); }
1162584980-google-io
libprojects/abs/src/com/actionbarsherlock/internal/view/View_OnAttachStateChangeListener.java
Java
asf20
211