List of usage examples for android.os Bundle getParcelableArrayList
@Nullable public <T extends Parcelable> ArrayList<T> getParcelableArrayList(@Nullable String key)
From source file:org.opendatakit.survey.activities.MainMenuActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // android.os.Debug.waitForDebugger(); submenuPage = getIntentExtras().getString("_sync_state"); try {// w ww . j a v a2 s . co m // ensure that we have a BackgroundTaskFragment... // create it programmatically because if we place it in the // layout XML, it will be recreated with each screen rotation // and we don't want that!!! mPropertyManager = new PropertyManager(this); // must be at the beginning of any activity that can be called from an // external intent setAppName(ODKFileUtils.getOdkDefaultAppName()); Uri uri = getIntent().getData(); Uri formUri = null; if (uri != null) { // initialize to the URI, then we will customize further based upon the // savedInstanceState... final Uri uriFormsProvider = FormsProviderAPI.CONTENT_URI; final Uri uriWebView = UrlUtils.getWebViewContentUri(this); if (uri.getScheme().equalsIgnoreCase(uriFormsProvider.getScheme()) && uri.getAuthority().equalsIgnoreCase(uriFormsProvider.getAuthority())) { List<String> segments = uri.getPathSegments(); if (segments != null && segments.size() == 1) { String appName = segments.get(0); setAppName(appName); } else if (segments != null && segments.size() >= 2) { String appName = segments.get(0); setAppName(appName); String tableId = segments.get(1); String formId = (segments.size() > 2) ? segments.get(2) : null; formUri = Uri.withAppendedPath(Uri.withAppendedPath( Uri.withAppendedPath(FormsProviderAPI.CONTENT_URI, appName), tableId), formId); } else { createErrorDialog(getString(R.string.invalid_uri_expecting_n_segments, uri.toString(), 2), EXIT); return; } } else if (uri.getScheme().equals(uriWebView.getScheme()) && uri.getAuthority().equals(uriWebView.getAuthority()) && uri.getPort() == uriWebView.getPort()) { List<String> segments = uri.getPathSegments(); if (segments != null && segments.size() == 1) { String appName = segments.get(0); setAppName(appName); } else { createErrorDialog(getString(R.string.invalid_uri_expecting_one_segment, uri.toString()), EXIT); return; } } else { createErrorDialog(getString(R.string.unrecognized_uri, uri.toString(), uriWebView.toString(), uriFormsProvider.toString()), EXIT); return; } } if (savedInstanceState != null) { // if appName is explicitly set, use it... setAppName(savedInstanceState.containsKey(IntentConsts.INTENT_KEY_APP_NAME) ? savedInstanceState.getString(IntentConsts.INTENT_KEY_APP_NAME) : getAppName()); if (savedInstanceState.containsKey(CONFLICT_TABLES)) { mConflictTables = savedInstanceState.getBundle(CONFLICT_TABLES); } } try { String appName = getAppName(); if (appName != null && appName.length() != 0) { ODKFileUtils.verifyExternalStorageAvailability(); ODKFileUtils.assertDirectoryStructure(appName); } } catch (RuntimeException e) { createErrorDialog(e.getMessage(), EXIT); return; } WebLogger.getLogger(getAppName()).i(t, "Starting up, creating directories"); if (savedInstanceState != null) { // if we are restoring, assume that initialization has already occurred. dispatchStringWaitingForData = savedInstanceState.containsKey(DISPATCH_STRING_WAITING_FOR_DATA) ? savedInstanceState.getString(DISPATCH_STRING_WAITING_FOR_DATA) : null; actionWaitingForData = savedInstanceState.containsKey(ACTION_WAITING_FOR_DATA) ? savedInstanceState.getString(ACTION_WAITING_FOR_DATA) : null; currentFragment = ScreenList.valueOf(savedInstanceState.containsKey(CURRENT_FRAGMENT) ? savedInstanceState.getString(CURRENT_FRAGMENT) : currentFragment.name()); if (savedInstanceState.containsKey(FORM_URI)) { FormIdStruct newForm = FormIdStruct.retrieveFormIdStruct(getContentResolver(), Uri.parse(savedInstanceState.getString(FORM_URI))); if (newForm != null) { setAppName(newForm.appName); setCurrentForm(newForm); } } setInstanceId( savedInstanceState.containsKey(INSTANCE_ID) ? savedInstanceState.getString(INSTANCE_ID) : getInstanceId()); setUploadTableId(savedInstanceState.containsKey(UPLOAD_TABLE_ID) ? savedInstanceState.getString(UPLOAD_TABLE_ID) : getUploadTableId()); String tmpScreenPath = savedInstanceState.containsKey(SCREEN_PATH) ? savedInstanceState.getString(SCREEN_PATH) : getScreenPath(); String tmpControllerState = savedInstanceState.containsKey(CONTROLLER_STATE) ? savedInstanceState.getString(CONTROLLER_STATE) : getControllerState(); setSectionScreenState(tmpScreenPath, tmpControllerState); setAuxillaryHash(savedInstanceState.containsKey(AUXILLARY_HASH) ? savedInstanceState.getString(AUXILLARY_HASH) : getAuxillaryHash()); if (savedInstanceState.containsKey(SESSION_VARIABLES)) { sessionVariables = savedInstanceState.getBundle(SESSION_VARIABLES); } if (savedInstanceState.containsKey(SECTION_STATE_SCREEN_HISTORY)) { sectionStateScreenHistory = savedInstanceState .getParcelableArrayList(SECTION_STATE_SCREEN_HISTORY); } if (savedInstanceState.containsKey(QUEUED_ACTIONS)) { String[] actionOutcomesArray = savedInstanceState.getStringArray(QUEUED_ACTIONS); queuedActions.clear(); queuedActions.addAll(Arrays.asList(actionOutcomesArray)); } if (savedInstanceState != null && savedInstanceState.containsKey(RESPONSE_JSON)) { String[] pendingResponseJSON = savedInstanceState.getStringArray(RESPONSE_JSON); queueResponseJSON.addAll(Arrays.asList(pendingResponseJSON)); } } else if (formUri != null) { // request specifies a specific formUri -- try to open that FormIdStruct newForm = FormIdStruct.retrieveFormIdStruct(getContentResolver(), formUri); if (newForm == null) { // can't find it -- launch the initialization dialog to hopefully // discover it. WebLogger.getLogger(getAppName()).i(t, "onCreate -- calling setRunInitializationTask"); ((Survey) getApplication()).setRunInitializationTask(getAppName()); currentFragment = ScreenList.WEBKIT; } else { transitionToFormHelper(uri, newForm); } } } catch (Exception e) { createErrorDialog(e.getMessage(), EXIT); } finally { setContentView(R.layout.main_screen); ActionBar actionBar = getActionBar(); actionBar.show(); } }
From source file:fr.univsavoie.ltp.client.MainActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Appliquer le thme LTP a l'ActionBar //setTheme(R.style.Theme_ltp); // Cration de l'activit principale setContentView(R.layout.activity_main); // Instancier les classes utiles setPopup(new Popup(this)); setSession(new Session(this)); setTools(new Tools(this)); // Afficher la ActionBar ActionBar mActionBar = getSupportActionBar(); mActionBar.setHomeButtonEnabled(true); mActionBar.setDisplayShowHomeEnabled(true); // MapView settings map = (MapView) findViewById(R.id.openmapview); map.setTileSource(TileSourceFactory.MAPNIK); map.setBuiltInZoomControls(false);/*from w ww. j av a2s . c o m*/ map.setMultiTouchControls(true); // MapController settings mapController = map.getController(); //To use MapEventsReceiver methods, we add a MapEventsOverlay: overlay = new MapEventsOverlay(this, this); map.getOverlays().add(overlay); boolean isWifiEnabled = false; boolean isGPSEnabled = false; // Vrifier si le wifi ou le rseau mobile est activ final ConnectivityManager connMgr = (ConnectivityManager) this .getSystemService(Context.CONNECTIVITY_SERVICE); final NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); final NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if (wifi.isAvailable() && (wifi.getDetailedState() == DetailedState.CONNECTING || wifi.getDetailedState() == DetailedState.CONNECTED)) { Toast.makeText(this, R.string.toast_wifi, Toast.LENGTH_LONG).show(); isWifiEnabled = true; } else if (mobile.isAvailable() && (mobile.getDetailedState() == DetailedState.CONNECTING || mobile.getDetailedState() == DetailedState.CONNECTED)) { Toast.makeText(this, R.string.toast_3G, Toast.LENGTH_LONG).show(); } else { Toast.makeText(this, R.string.toast_aucun_reseau, Toast.LENGTH_LONG).show(); } // Obtenir le service de localisation locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); // Verifier si le service de localisation GPS est actif, le cas echeant, tester le rseau if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30 * 1000, 250.0f, this); location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); isGPSEnabled = true; } else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30 * 1000, 250.0f, this); location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); } // Afficher une boite de dialogue et proposer d'activer un ou plusieurs services pas actifs if (!isWifiEnabled || !isGPSEnabled) { //getTools().showSettingsAlert(this, isWifiEnabled, isGPSEnabled); } // Si on a une localisation, on dfinit ses coordonnes geopoint if (location != null) { startPoint = new GeoPoint(location.getLatitude(), location.getLongitude()); } else { // Sinon, on indique des paramtres par dfaut location = getTools().getLastKnownLocation(locationManager); if (location == null) { location = new Location(""); location.setLatitude(46.227638); location.setLongitude(2.213749000000); } startPoint = new GeoPoint(46.227638, 2.213749000000); } setLongitude(location.getLongitude()); setLatitude(location.getLatitude()); destinationPoint = null; viaPoints = new ArrayList<GeoPoint>(); // On recupre quelques paramtres de la session prcdents si possible if (savedInstanceState == null) { mapController.setZoom(15); mapController.setCenter(startPoint); } else { mapController.setZoom(savedInstanceState.getInt("zoom_level")); mapController.setCenter((GeoPoint) savedInstanceState.getParcelable("map_center")); } // Crer un overlay sur la carte pour afficher notre point de dpart myLocationOverlay = new SimpleLocationOverlay(this, new DefaultResourceProxyImpl(this)); map.getOverlays().add(myLocationOverlay); myLocationOverlay.setLocation(startPoint); // Boutton pour zoomer la carte ImageButton btZoomIn = (ImageButton) findViewById(R.id.btZoomIn); btZoomIn.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { map.getController().zoomIn(); } }); // Boutton pour dezoomer la carte ImageButton btZoomOut = (ImageButton) findViewById(R.id.btZoomOut); btZoomOut.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { map.getController().zoomOut(); } }); // Pointeurs d'itinrairea: final ArrayList<ExtendedOverlayItem> waypointsItems = new ArrayList<ExtendedOverlayItem>(); itineraryMarkers = new ItemizedOverlayWithBubble<ExtendedOverlayItem>(this, waypointsItems, map, new ViaPointInfoWindow(R.layout.itinerary_bubble, map)); map.getOverlays().add(itineraryMarkers); //updateUIWithItineraryMarkers(); Button searchButton = (Button) findViewById(R.id.buttonSearch); searchButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { handleSearchLocationButton(); } }); //context menu for clicking on the map is registered on this button. registerForContextMenu(searchButton); // Routes et Itinraires final ArrayList<ExtendedOverlayItem> roadItems = new ArrayList<ExtendedOverlayItem>(); roadNodeMarkers = new ItemizedOverlayWithBubble<ExtendedOverlayItem>(this, roadItems, map); map.getOverlays().add(roadNodeMarkers); if (savedInstanceState != null) { mRoad = savedInstanceState.getParcelable("road"); updateUIWithRoad(mRoad); } //POIs: //POI search interface: String[] poiTags = getResources().getStringArray(R.array.poi_tags); poiTagText = (AutoCompleteTextView) findViewById(R.id.poiTag); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, poiTags); poiTagText.setAdapter(adapter); Button setPOITagButton = (Button) findViewById(R.id.buttonSetPOITag); setPOITagButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //Hide the soft keyboard: InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(poiTagText.getWindowToken(), 0); //Start search: getPOIAsync(poiTagText.getText().toString()); } }); //POI markers: final ArrayList<ExtendedOverlayItem> poiItems = new ArrayList<ExtendedOverlayItem>(); poiMarkers = new ItemizedOverlayWithBubble<ExtendedOverlayItem>(this, poiItems, map, new POIInfoWindow(map)); map.getOverlays().add(poiMarkers); if (savedInstanceState != null) { mPOIs = savedInstanceState.getParcelableArrayList("poi"); updateUIWithPOI(mPOIs); } // Load friends ListView lvListeFriends = (ListView) findViewById(R.id.listViewFriends); //lvListeFriends.setBackgroundResource(R.drawable.listview_roundcorner_item); lvListeFriends.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> adapter, View v, int position, long id) { Friends item = (Friends) adapter.getItemAtPosition(position); if (item.getLongitude() != 0.0 && item.getLatitude() != 0.0) { destinationPoint = new GeoPoint(item.getLongitude(), item.getLatitude()); markerDestination = putMarkerItem(markerDestination, destinationPoint, DEST_INDEX, R.string.destination, R.drawable.marker_destination, -1); getRoadAsync(); map.getController().setCenter(destinationPoint); } else { Toast.makeText(MainActivity.this, R.string.toast_friend_statut, Toast.LENGTH_LONG).show(); } } }); viewMapFilters = (ScrollView) this.findViewById(R.id.scrollViewMapFilters); viewMapFilters.setVisibility(View.GONE); // Initialiser tout ce qui est donnes utilisateur propres l'activit init(); getTools().relocateUser(mapController, map, myLocationOverlay, location); }
From source file:com.keylesspalace.tusky.ComposeActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); String theme = preferences.getString("appTheme", ThemeUtils.APP_THEME_DEFAULT); if (theme.equals("black")) { setTheme(R.style.TuskyDialogActivityBlackTheme); }/* w w w. j a v a2 s . com*/ setContentView(R.layout.activity_compose); replyTextView = findViewById(R.id.composeReplyView); replyContentTextView = findViewById(R.id.composeReplyContentView); textEditor = findViewById(R.id.composeEditField); mediaPreviewBar = findViewById(R.id.compose_media_preview_bar); contentWarningBar = findViewById(R.id.composeContentWarningBar); contentWarningEditor = findViewById(R.id.composeContentWarningField); charactersLeft = findViewById(R.id.composeCharactersLeftView); tootButton = findViewById(R.id.composeTootButton); pickButton = findViewById(R.id.composeAddMediaButton); visibilityButton = findViewById(R.id.composeToggleVisibilityButton); contentWarningButton = findViewById(R.id.composeContentWarningButton); emojiButton = findViewById(R.id.composeEmojiButton); hideMediaToggle = findViewById(R.id.composeHideMediaButton); emojiView = findViewById(R.id.emojiView); emojiList = Collections.emptyList(); saveTootHelper = new SaveTootHelper(database.tootDao(), this); // Setup the toolbar. Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setTitle(null); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setDisplayShowHomeEnabled(true); Drawable closeIcon = AppCompatResources.getDrawable(this, R.drawable.ic_close_24dp); ThemeUtils.setDrawableTint(this, closeIcon, R.attr.compose_close_button_tint); actionBar.setHomeAsUpIndicator(closeIcon); } // setup the account image final AccountEntity activeAccount = accountManager.getActiveAccount(); if (activeAccount != null) { ImageView composeAvatar = findViewById(R.id.composeAvatar); if (TextUtils.isEmpty(activeAccount.getProfilePictureUrl())) { composeAvatar.setImageResource(R.drawable.avatar_default); } else { Picasso.with(this).load(activeAccount.getProfilePictureUrl()).error(R.drawable.avatar_default) .placeholder(R.drawable.avatar_default).into(composeAvatar); } composeAvatar.setContentDescription( getString(R.string.compose_active_account_description, activeAccount.getFullName())); mastodonApi.getInstance().enqueue(new Callback<Instance>() { @Override public void onResponse(@NonNull Call<Instance> call, @NonNull Response<Instance> response) { if (response.isSuccessful() && response.body().getMaxTootChars() != null) { maximumTootCharacters = response.body().getMaxTootChars(); updateVisibleCharactersLeft(); cacheInstanceMetadata(activeAccount); } } @Override public void onFailure(@NonNull Call<Instance> call, @NonNull Throwable t) { Log.w(TAG, "error loading instance data", t); loadCachedInstanceMetadata(activeAccount); } }); mastodonApi.getCustomEmojis().enqueue(new Callback<List<Emoji>>() { @Override public void onResponse(@NonNull Call<List<Emoji>> call, @NonNull Response<List<Emoji>> response) { emojiList = response.body(); setEmojiList(emojiList); cacheInstanceMetadata(activeAccount); } @Override public void onFailure(@NonNull Call<List<Emoji>> call, @NonNull Throwable t) { Log.w(TAG, "error loading custom emojis", t); loadCachedInstanceMetadata(activeAccount); } }); } else { // do not do anything when not logged in, activity will be finished in super.onCreate() anyway return; } composeOptionsView = findViewById(R.id.composeOptionsBottomSheet); composeOptionsView.setListener(this); composeOptionsBehavior = BottomSheetBehavior.from(composeOptionsView); composeOptionsBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); addMediaBehavior = BottomSheetBehavior.from(findViewById(R.id.addMediaBottomSheet)); emojiBehavior = BottomSheetBehavior.from(emojiView); emojiView.setLayoutManager(new GridLayoutManager(this, 3, GridLayoutManager.HORIZONTAL, false)); enableButton(emojiButton, false, false); // Setup the interface buttons. tootButton.setOnClickListener(v -> onSendClicked()); pickButton.setOnClickListener(v -> openPickDialog()); visibilityButton.setOnClickListener(v -> showComposeOptions()); contentWarningButton.setOnClickListener(v -> onContentWarningChanged()); emojiButton.setOnClickListener(v -> showEmojis()); hideMediaToggle.setOnClickListener(v -> toggleHideMedia()); TextView actionPhotoTake = findViewById(R.id.action_photo_take); TextView actionPhotoPick = findViewById(R.id.action_photo_pick); int textColor = ThemeUtils.getColor(this, android.R.attr.textColorTertiary); Drawable cameraIcon = new IconicsDrawable(this, GoogleMaterial.Icon.gmd_camera_alt).color(textColor) .sizeDp(18); TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(actionPhotoTake, cameraIcon, null, null, null); Drawable imageIcon = new IconicsDrawable(this, GoogleMaterial.Icon.gmd_image).color(textColor).sizeDp(18); TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(actionPhotoPick, imageIcon, null, null, null); actionPhotoTake.setOnClickListener(v -> initiateCameraApp()); actionPhotoPick.setOnClickListener(v -> onMediaPick()); thumbnailViewSize = getResources().getDimensionPixelSize(R.dimen.compose_media_preview_size); /* Initialise all the state, or restore it from a previous run, to determine a "starting" * state. */ Status.Visibility startingVisibility = Status.Visibility.UNKNOWN; boolean startingHideText; ArrayList<SavedQueuedMedia> savedMediaQueued = null; if (savedInstanceState != null) { startingVisibility = Status.Visibility .byNum(savedInstanceState.getInt("statusVisibility", Status.Visibility.PUBLIC.getNum())); statusMarkSensitive = savedInstanceState.getBoolean("statusMarkSensitive"); startingHideText = savedInstanceState.getBoolean("statusHideText"); // Keep these until everything needed to put them in the queue is finished initializing. savedMediaQueued = savedInstanceState.getParcelableArrayList("savedMediaQueued"); // These are for restoring an in-progress commit content operation. InputContentInfoCompat previousInputContentInfo = InputContentInfoCompat .wrap(savedInstanceState.getParcelable("commitContentInputContentInfo")); int previousFlags = savedInstanceState.getInt("commitContentFlags"); if (previousInputContentInfo != null) { onCommitContentInternal(previousInputContentInfo, previousFlags); } photoUploadUri = savedInstanceState.getParcelable("photoUploadUri"); } else { statusMarkSensitive = false; startingHideText = false; photoUploadUri = null; } /* If the composer is started up as a reply to another post, override the "starting" state * based on what the intent from the reply request passes. */ Intent intent = getIntent(); String[] mentionedUsernames = null; ArrayList<String> loadedDraftMediaUris = null; inReplyToId = null; if (intent != null) { if (startingVisibility == Status.Visibility.UNKNOWN) { Status.Visibility preferredVisibility = Status.Visibility.byString( preferences.getString("defaultPostPrivacy", Status.Visibility.PUBLIC.serverString())); Status.Visibility replyVisibility = Status.Visibility .byNum(intent.getIntExtra(REPLY_VISIBILITY_EXTRA, Status.Visibility.UNKNOWN.getNum())); startingVisibility = Status.Visibility .byNum(Math.max(preferredVisibility.getNum(), replyVisibility.getNum())); } inReplyToId = intent.getStringExtra(IN_REPLY_TO_ID_EXTRA); mentionedUsernames = intent.getStringArrayExtra(MENTIONED_USERNAMES_EXTRA); String contentWarning = intent.getStringExtra(CONTENT_WARNING_EXTRA); if (contentWarning != null) { startingHideText = !contentWarning.isEmpty(); if (startingHideText) { startingContentWarning = contentWarning; } } // If come from SavedTootActivity String savedTootText = intent.getStringExtra(SAVED_TOOT_TEXT_EXTRA); if (!TextUtils.isEmpty(savedTootText)) { startingText = savedTootText; textEditor.setText(savedTootText); } String savedJsonUrls = intent.getStringExtra(SAVED_JSON_URLS_EXTRA); if (!TextUtils.isEmpty(savedJsonUrls)) { // try to redo a list of media loadedDraftMediaUris = new Gson().fromJson(savedJsonUrls, new TypeToken<ArrayList<String>>() { }.getType()); } int savedTootUid = intent.getIntExtra(SAVED_TOOT_UID_EXTRA, 0); if (savedTootUid != 0) { this.savedTootUid = savedTootUid; } if (intent.hasExtra(REPLYING_STATUS_AUTHOR_USERNAME_EXTRA)) { replyTextView.setVisibility(View.VISIBLE); String username = intent.getStringExtra(REPLYING_STATUS_AUTHOR_USERNAME_EXTRA); replyTextView.setText(getString(R.string.replying_to, username)); Drawable arrowDownIcon = new IconicsDrawable(this, GoogleMaterial.Icon.gmd_arrow_drop_down) .sizeDp(12); ThemeUtils.setDrawableTint(this, arrowDownIcon, android.R.attr.textColorTertiary); TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(replyTextView, null, null, arrowDownIcon, null); replyTextView.setOnClickListener(v -> { TransitionManager.beginDelayedTransition((ViewGroup) replyContentTextView.getParent()); if (replyContentTextView.getVisibility() != View.VISIBLE) { replyContentTextView.setVisibility(View.VISIBLE); Drawable arrowUpIcon = new IconicsDrawable(this, GoogleMaterial.Icon.gmd_arrow_drop_up) .sizeDp(12); ThemeUtils.setDrawableTint(this, arrowUpIcon, android.R.attr.textColorTertiary); TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(replyTextView, null, null, arrowUpIcon, null); } else { replyContentTextView.setVisibility(View.GONE); TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(replyTextView, null, null, arrowDownIcon, null); } }); } if (intent.hasExtra(REPLYING_STATUS_CONTENT_EXTRA)) { replyContentTextView.setText(intent.getStringExtra(REPLYING_STATUS_CONTENT_EXTRA)); } } // After the starting state is finalised, the interface can be set to reflect this state. setStatusVisibility(startingVisibility); updateHideMediaToggle(); updateVisibleCharactersLeft(); // Setup the main text field. textEditor.setOnCommitContentListener(this); final int mentionColour = textEditor.getLinkTextColors().getDefaultColor(); SpanUtilsKt.highlightSpans(textEditor.getText(), mentionColour); textEditor.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable editable) { SpanUtilsKt.highlightSpans(editable, mentionColour); updateVisibleCharactersLeft(); } }); textEditor.setAdapter(new MentionAutoCompleteAdapter(this, R.layout.item_autocomplete, this)); textEditor.setTokenizer(new MentionTokenizer()); // Add any mentions to the text field when a reply is first composed. if (mentionedUsernames != null) { StringBuilder builder = new StringBuilder(); for (String name : mentionedUsernames) { builder.append('@'); builder.append(name); builder.append(' '); } startingText = builder.toString(); textEditor.setText(startingText); textEditor.setSelection(textEditor.length()); } // work around Android platform bug -> https://issuetracker.google.com/issues/67102093 if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O || Build.VERSION.SDK_INT == Build.VERSION_CODES.O_MR1) { textEditor.setLayerType(View.LAYER_TYPE_SOFTWARE, null); } // Initialise the content warning editor. contentWarningEditor.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { updateVisibleCharactersLeft(); } @Override public void afterTextChanged(Editable s) { } }); showContentWarning(startingHideText); if (startingContentWarning != null) { contentWarningEditor.setText(startingContentWarning); } // Initialise the empty media queue state. waitForMediaLatch = new CountUpDownLatch(); // These can only be added after everything affected by the media queue is initialized. if (!ListUtils.isEmpty(loadedDraftMediaUris)) { for (String uriString : loadedDraftMediaUris) { Uri uri = Uri.parse(uriString); long mediaSize = MediaUtils.getMediaSize(getContentResolver(), uri); pickMedia(uri, mediaSize); } } else if (savedMediaQueued != null) { for (SavedQueuedMedia item : savedMediaQueued) { Bitmap preview = MediaUtils.getImageThumbnail(getContentResolver(), item.uri, thumbnailViewSize); addMediaToQueue(item.id, item.type, preview, item.uri, item.mediaSize, item.readyStage, item.description); } } else if (intent != null && savedInstanceState == null) { /* Get incoming images being sent through a share action from another app. Only do this * when savedInstanceState is null, otherwise both the images from the intent and the * instance state will be re-queued. */ String type = intent.getType(); if (type != null) { if (type.startsWith("image/")) { List<Uri> uriList = new ArrayList<>(); if (intent.getAction() != null) { switch (intent.getAction()) { case Intent.ACTION_SEND: { Uri uri = intent.getParcelableExtra(Intent.EXTRA_STREAM); if (uri != null) { uriList.add(uri); } break; } case Intent.ACTION_SEND_MULTIPLE: { ArrayList<Uri> list = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM); if (list != null) { for (Uri uri : list) { if (uri != null) { uriList.add(uri); } } } break; } } } for (Uri uri : uriList) { long mediaSize = MediaUtils.getMediaSize(getContentResolver(), uri); pickMedia(uri, mediaSize); } } else if (type.equals("text/plain")) { String action = intent.getAction(); if (action != null && action.equals(Intent.ACTION_SEND)) { String text = intent.getStringExtra(Intent.EXTRA_TEXT); if (text != null) { int start = Math.max(textEditor.getSelectionStart(), 0); int end = Math.max(textEditor.getSelectionEnd(), 0); int left = Math.min(start, end); int right = Math.max(start, end); textEditor.getText().replace(left, right, text, 0, text.length()); } } } } } textEditor.requestFocus(); }
From source file:com.amaze.carbonfilemanager.activities.MainActivity.java
/** * Called when the activity is first created. *//*from w ww . jav a 2 s .com*/ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initialisePreferences(); initializeInteractiveShell(); dataUtils = new DataUtils(); dataUtils.registerOnDataChangedListener(this); setContentView(R.layout.main_toolbar); initialiseViews(); tabHandler = new TabHandler(this); mImageLoader = AppConfig.getInstance().getImageLoader(); utils = getFutils(); mainActivityHelper = new MainActivityHelper(this); initialiseFab(); // TODO: Create proper SQLite database handler class with calls to database from background thread history = new HistoryManager(this, "Table2"); history.initializeTable(DataUtils.HISTORY, 0); history.initializeTable(DataUtils.HIDDEN, 0); grid = new HistoryManager(this, "listgridmodes"); grid.initializeTable(DataUtils.LIST, 0); grid.initializeTable(DataUtils.GRID, 0); grid.initializeTable(DataUtils.BOOKS, 1); grid.initializeTable(DataUtils.SMB, 1); if (!sharedPref.getBoolean("booksadded", false)) { grid.make(DataUtils.BOOKS); sharedPref.edit().putBoolean("booksadded", true).commit(); } dataUtils.setHiddenfiles(history.readTable(DataUtils.HIDDEN)); dataUtils.setGridfiles(grid.readTable(DataUtils.GRID)); dataUtils.setListfiles(grid.readTable(DataUtils.LIST)); // initialize g+ api client as per preferences if (sharedPref.getBoolean("plus_pic", false)) { mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this) .addOnConnectionFailedListener(this).addApi(Plus.API).addScope(Plus.SCOPE_PLUS_LOGIN).build(); } if (CloudSheetFragment.isCloudProviderAvailable(this)) { getSupportLoaderManager().initLoader(REQUEST_CODE_CLOUD_LIST_KEY_CLOUD, null, this); } util = new IconUtils(sharedPref, this); icons = new IconUtils(sharedPref, this); timer = new CountDownTimer(5000, 1000) { @Override public void onTick(long l) { } @Override public void onFinish() { utils.crossfadeInverse(buttons, pathbar); } }; path = getIntent().getStringExtra("path"); openProcesses = getIntent().getBooleanExtra(KEY_INTENT_PROCESS_VIEWER, false); try { intent = getIntent(); if (intent.getStringArrayListExtra(TAG_INTENT_FILTER_FAILED_OPS) != null) { ArrayList<BaseFile> failedOps = intent.getParcelableArrayListExtra(TAG_INTENT_FILTER_FAILED_OPS); if (failedOps != null) { mainActivityHelper.showFailedOperationDialog(failedOps, intent.getBooleanExtra("move", false), this); } } if (intent.getAction() != null) { if (intent.getAction().equals(Intent.ACTION_GET_CONTENT)) { // file picker intent mReturnIntent = true; Toast.makeText(this, getString(R.string.pick_a_file), Toast.LENGTH_LONG).show(); } else if (intent.getAction().equals(RingtoneManager.ACTION_RINGTONE_PICKER)) { // ringtone picker intent mReturnIntent = true; mRingtonePickerIntent = true; Toast.makeText(this, getString(R.string.pick_a_file), Toast.LENGTH_LONG).show(); } else if (intent.getAction().equals(Intent.ACTION_VIEW)) { // zip viewer intent Uri uri = intent.getData(); openzip = true; zippath = uri.toString(); } } } catch (Exception e) { e.printStackTrace(); } if (savedInstanceState != null) { selectedStorage = savedInstanceState.getInt("selectitem", SELECT_0); } refreshDrawer(); // setting window background color instead of each item, in order to reduce pixel overdraw if (getAppTheme().equals(AppTheme.LIGHT)) { /*if(Main.IS_LIST) getWindow().setBackgroundDrawableResource(android.R.color.white); else getWindow().setBackgroundDrawableResource(R.color.grid_background_light); */ getWindow().setBackgroundDrawableResource(android.R.color.white); } else { getWindow().setBackgroundDrawableResource(R.color.holo_dark_background); } if (savedInstanceState == null) { if (openProcesses) { android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager() .beginTransaction(); transaction.replace(R.id.content_frame, new ProcessViewer(), KEY_INTENT_PROCESS_VIEWER); //transaction.addToBackStack(null); selectedStorage = SELECT_102; openProcesses = false; //title.setText(utils.getString(con, R.string.process_viewer)); //Commit the transaction transaction.commit(); supportInvalidateOptionsMenu(); } else if (intent.getAction() != null && intent.getAction().equals(TileService.ACTION_QS_TILE_PREFERENCES)) { // tile preferences, open ftp fragment android.support.v4.app.FragmentTransaction transaction2 = getSupportFragmentManager() .beginTransaction(); transaction2.replace(R.id.content_frame, new FTPServerFragment()); findViewById(R.id.lin).animate().translationY(0).setInterpolator(new DecelerateInterpolator(2)) .start(); selectedStorage = SELECT_MINUS_2; adapter.toggleChecked(false); transaction2.commit(); } else { if (path != null && path.length() > 0) { HFile file = new HFile(OpenMode.UNKNOWN, path); file.generateMode(this); if (file.isDirectory()) goToMain(path); else { goToMain(""); utils.openFile(new File(path), this); } } else { goToMain(""); } } } else { COPY_PATH = savedInstanceState.getParcelableArrayList("COPY_PATH"); MOVE_PATH = savedInstanceState.getParcelableArrayList("MOVE_PATH"); oppathe = savedInstanceState.getString("oppathe"); oppathe1 = savedInstanceState.getString("oppathe1"); oparrayList = savedInstanceState.getParcelableArrayList("oparrayList"); operation = savedInstanceState.getInt("operation"); selectedStorage = savedInstanceState.getInt("selectitem", SELECT_0); //mainFragment = (Main) savedInstanceState.getParcelable("main_fragment"); adapter.toggleChecked(selectedStorage); } if (getAppTheme().equals(AppTheme.DARK)) { mDrawerList.setBackgroundColor(ContextCompat.getColor(this, R.color.holo_dark_background)); } mDrawerList.setDivider(null); if (!isDrawerLocked) { mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */ mDrawerLayout, /* DrawerLayout object */ R.drawable.ic_drawer_l, /* nav drawer image to replace 'Up' caret */ R.string.drawer_open, /* "open drawer" description for accessibility */ R.string.drawer_close /* "close drawer" description for accessibility */ ) { public void onDrawerClosed(View view) { mainActivity.onDrawerClosed(); } public void onDrawerOpened(View drawerView) { //title.setText("Amaze File Manager"); // creates call to onPrepareOptionsMenu() } }; mDrawerLayout.setDrawerListener(mDrawerToggle); getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_drawer_l); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); mDrawerToggle.syncState(); } /*((ImageButton) findViewById(R.id.drawer_buttton)).setOnClickListener(new ImageView.OnClickListener() { @Override public void onClick(View view) { if (mDrawerLayout.isDrawerOpen(mDrawerLinear)) { mDrawerLayout.closeDrawer(mDrawerLinear); } else mDrawerLayout.openDrawer(mDrawerLinear); } });*/ if (mDrawerToggle != null) { mDrawerToggle.setDrawerIndicatorEnabled(true); mDrawerToggle.setHomeAsUpIndicator(R.drawable.ic_drawer_l); } //recents header color implementation if (SDK_INT >= 21) { ActivityManager.TaskDescription taskDescription = new ActivityManager.TaskDescription("Amaze", ((BitmapDrawable) getResources().getDrawable(R.mipmap.ic_launcher)).getBitmap(), getColorPreference().getColor(ColorUsage.getPrimary(MainActivity.currentTab))); setTaskDescription(taskDescription); } }
From source file:com.krayzk9s.imgurholo.ui.SingleImageFragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); final ImgurHoloActivity activity = (ImgurHoloActivity) getActivity(); final SharedPreferences settings = activity.getApiCall().settings; sort = settings.getString("CommentSort", "Best"); boolean newData = true; if (commentData != null) { newData = false;/*from w w w.jav a2 s .c o m*/ } mainView = inflater.inflate(R.layout.single_image_layout, container, false); String[] mMenuList = getResources().getStringArray(R.array.emptyList); if (commentAdapter == null) commentAdapter = new CommentAdapter(mainView.getContext()); commentLayout = (ListView) mainView.findViewById(R.id.comment_thread); commentLayout.setChoiceMode(ListView.CHOICE_MODE_SINGLE); if (settings.getString("theme", MainActivity.HOLO_LIGHT).equals(MainActivity.HOLO_LIGHT)) imageLayoutView = (LinearLayout) View.inflate(getActivity(), R.layout.image_view, null); else imageLayoutView = (LinearLayout) View.inflate(getActivity(), R.layout.dark_image_view, null); mPullToRefreshLayout = (PullToRefreshLayout) mainView.findViewById(R.id.ptr_layout); ActionBarPullToRefresh.from(getActivity()) // Mark All Children as pullable .allChildrenArePullable() // Set the OnRefreshListener .listener(this) // Finally commit the setup to our PullToRefreshLayout .setup(mPullToRefreshLayout); if (savedInstanceState != null && newData) { imageData = savedInstanceState.getParcelable("imageData"); inGallery = savedInstanceState.getBoolean("inGallery"); } LinearLayout layout = (LinearLayout) imageLayoutView.findViewById(R.id.image_buttons); TextView imageDetails = (TextView) imageLayoutView.findViewById(R.id.single_image_details); layout.setVisibility(View.VISIBLE); ImageButton imageFullscreen = (ImageButton) imageLayoutView.findViewById(R.id.fullscreen); imageUpvote = (ImageButton) imageLayoutView.findViewById(R.id.rating_good); imageDownvote = (ImageButton) imageLayoutView.findViewById(R.id.rating_bad); ImageButton imageFavorite = (ImageButton) imageLayoutView.findViewById(R.id.rating_favorite); imageComment = (ImageButton) imageLayoutView.findViewById(R.id.comment); ImageButton imageUser = (ImageButton) imageLayoutView.findViewById(R.id.user); imageScore = (TextView) imageLayoutView.findViewById(R.id.single_image_score); TextView imageInfo = (TextView) imageLayoutView.findViewById(R.id.single_image_info); Log.d("imageData", imageData.getJSONObject().toString()); if (imageData.getJSONObject().has("ups")) { imageUpvote.setVisibility(View.VISIBLE); imageDownvote.setVisibility(View.VISIBLE); imageScore.setVisibility(View.VISIBLE); imageComment.setVisibility(View.VISIBLE); ImageUtils.updateImageFont(imageData, imageScore); } imageInfo.setVisibility(View.VISIBLE); ImageUtils.updateInfoFont(imageData, imageInfo); imageUser.setVisibility(View.VISIBLE); imageFavorite.setVisibility(View.VISIBLE); try { if (!imageData.getJSONObject().has("account_url") || imageData.getJSONObject().getString("account_url").equals("null") || imageData.getJSONObject().getString("account_url").equals("[deleted]")) imageUser.setVisibility(View.GONE); if (!imageData.getJSONObject().has("vote")) { imageUpvote.setVisibility(View.GONE); imageDownvote.setVisibility(View.GONE); } else { if (imageData.getJSONObject().getString("vote") != null && imageData.getJSONObject().getString("vote").equals("up")) imageUpvote.setImageResource(R.drawable.green_rating_good); else if (imageData.getJSONObject().getString("vote") != null && imageData.getJSONObject().getString("vote").equals("down")) imageDownvote.setImageResource(R.drawable.red_rating_bad); } if (imageData.getJSONObject().getString("favorite") != null && imageData.getJSONObject().getBoolean("favorite")) imageFavorite.setImageResource(R.drawable.green_rating_favorite); } catch (JSONException e) { Log.e("Error!", e.toString()); } imageFavorite.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ImageUtils.favoriteImage(singleImageFragment, imageData, (ImageButton) view, activity.getApiCall()); } }); imageUser.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ImageUtils.gotoUser(singleImageFragment, imageData); } }); imageComment.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Activity activity = getActivity(); final EditText newBody = new EditText(activity); newBody.setHint(R.string.body_hint_body); newBody.setLines(3); final TextView characterCount = new TextView(activity); characterCount.setText("140"); LinearLayout commentReplyLayout = new LinearLayout(activity); newBody.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { // } @Override public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { characterCount.setText(String.valueOf(140 - charSequence.length())); } @Override public void afterTextChanged(Editable editable) { for (int i = editable.length(); i > 0; i--) { if (editable.subSequence(i - 1, i).toString().equals("\n")) editable.replace(i - 1, i, ""); } } }); commentReplyLayout.setOrientation(LinearLayout.VERTICAL); commentReplyLayout.addView(newBody); commentReplyLayout.addView(characterCount); new AlertDialog.Builder(activity).setTitle(R.string.dialog_comment_on_image_title) .setView(commentReplyLayout) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if (newBody.getText() != null && newBody.getText().toString().length() < 141) { HashMap<String, Object> commentMap = new HashMap<String, Object>(); try { commentMap.put("comment", newBody.getText().toString()); commentMap.put("image_id", imageData.getJSONObject().getString("id")); Fetcher fetcher = new Fetcher(singleImageFragment, "3/comment/", ApiCall.POST, commentMap, ((ImgurHoloActivity) getActivity()).getApiCall(), POSTCOMMENT); fetcher.execute(); } catch (JSONException e) { Log.e("Error!", e.toString()); } } } }).setNegativeButton(R.string.dialog_answer_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // Do nothing. } }).show(); } }); imageUpvote.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ImageUtils.upVote(singleImageFragment, imageData, imageUpvote, imageDownvote, activity.getApiCall()); ImageUtils.updateImageFont(imageData, imageScore); } }); imageDownvote.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ImageUtils.downVote(singleImageFragment, imageData, imageUpvote, imageDownvote, activity.getApiCall()); ImageUtils.updateImageFont(imageData, imageScore); } }); if (popupWindow != null) { popupWindow.dismiss(); } popupWindow = new PopupWindow(); imageFullscreen.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ImageUtils.fullscreen(singleImageFragment, imageData, popupWindow, mainView); } }); ArrayAdapter<String> tempAdapter = new ArrayAdapter<String>(mainView.getContext(), R.layout.drawer_list_item, mMenuList); Log.d("URI", "YO I'M IN YOUR SINGLE FRAGMENT gallery:" + inGallery); imageView = (ImageView) imageLayoutView.findViewById(R.id.single_image_view); loadImage(); TextView imageTitle = (TextView) imageLayoutView.findViewById(R.id.single_image_title); TextView imageDescription = (TextView) imageLayoutView.findViewById(R.id.single_image_description); try { String size = String .valueOf(NumberFormat.getIntegerInstance() .format(imageData.getJSONObject().getInt(ImgurHoloActivity.IMAGE_DATA_WIDTH))) + "x" + NumberFormat.getIntegerInstance() .format(imageData.getJSONObject().getInt(ImgurHoloActivity.IMAGE_DATA_HEIGHT)) + " (" + NumberFormat.getIntegerInstance() .format(imageData.getJSONObject().getInt(ImgurHoloActivity.IMAGE_DATA_SIZE)) + "B)"; String initial = imageData.getJSONObject().getString(ImgurHoloActivity.IMAGE_DATA_TYPE) + " " + Html.fromHtml("•") + " " + size + " " + Html.fromHtml("•") + " " + "Views: " + NumberFormat.getIntegerInstance() .format(imageData.getJSONObject().getInt(ImgurHoloActivity.IMAGE_DATA_VIEWS)); imageDetails.setText(initial); Log.d("imagedata", imageData.getJSONObject().toString()); if (!imageData.getJSONObject().getString(ImgurHoloActivity.IMAGE_DATA_TITLE).equals("null")) imageTitle.setText(imageData.getJSONObject().getString(ImgurHoloActivity.IMAGE_DATA_TITLE)); else imageTitle.setVisibility(View.GONE); if (!imageData.getJSONObject().getString(ImgurHoloActivity.IMAGE_DATA_DESCRIPTION).equals("null")) { imageDescription .setText(imageData.getJSONObject().getString(ImgurHoloActivity.IMAGE_DATA_DESCRIPTION)); imageDescription.setVisibility(View.VISIBLE); } else imageDescription.setVisibility(View.GONE); commentLayout.addHeaderView(imageLayoutView); commentLayout.setAdapter(tempAdapter); } catch (JSONException e) { Log.e("Text Error!", e.toString()); } if ((savedInstanceState == null || commentData == null) && newData) { commentData = new JSONParcelable(); getComments(); commentLayout.setAdapter(commentAdapter); } else if (newData) { commentArray = savedInstanceState.getParcelableArrayList("commentData"); commentAdapter.addAll(commentArray); commentLayout.setAdapter(commentAdapter); commentAdapter.notifyDataSetChanged(); } else if (commentArray != null) { commentAdapter.addAll(commentArray); commentLayout.setAdapter(commentAdapter); commentAdapter.notifyDataSetChanged(); } return mainView; }