List of usage examples for android.graphics Color argb
@ColorInt public static int argb(float alpha, float red, float green, float blue)
From source file:com.gosuncn.core.util.view.StatusBarUtils.java
/** * ?? View/*from w ww . j av a 2s.co m*/ * * @param alpha ? * @return ?? View */ private static StatusBarView createTranslucentStatusBarView(Activity activity, int alpha) { // ?? StatusBarView statusBarView = new StatusBarView(activity); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight(activity)); statusBarView.setLayoutParams(params); statusBarView.setBackgroundColor(Color.argb(alpha, 0, 0, 0)); return statusBarView; }
From source file:com.google.android.apps.muzei.settings.ChooseSourceFragment.java
public void updateSources() { mSelectedSource = null;//from w w w. j a va2 s . c om Intent queryIntent = new Intent(ACTION_MUZEI_ART_SOURCE); PackageManager pm = getContext().getPackageManager(); mSources.clear(); List<ResolveInfo> resolveInfos = pm.queryIntentServices(queryIntent, PackageManager.GET_META_DATA); for (ResolveInfo ri : resolveInfos) { Source source = new Source(); source.label = ri.loadLabel(pm).toString(); source.icon = new BitmapDrawable(getResources(), generateSourceImage(ri.loadIcon(pm))); source.targetSdkVersion = ri.serviceInfo.applicationInfo.targetSdkVersion; source.componentName = new ComponentName(ri.serviceInfo.packageName, ri.serviceInfo.name); if (ri.serviceInfo.descriptionRes != 0) { try { Context packageContext = getContext() .createPackageContext(source.componentName.getPackageName(), 0); Resources packageRes = packageContext.getResources(); source.description = packageRes.getString(ri.serviceInfo.descriptionRes); } catch (PackageManager.NameNotFoundException | Resources.NotFoundException e) { Log.e(TAG, "Can't read package resources for source " + source.componentName); } } Bundle metaData = ri.serviceInfo.metaData; source.color = Color.WHITE; if (metaData != null) { String settingsActivity = metaData.getString("settingsActivity"); if (!TextUtils.isEmpty(settingsActivity)) { source.settingsActivity = ComponentName .unflattenFromString(ri.serviceInfo.packageName + "/" + settingsActivity); } String setupActivity = metaData.getString("setupActivity"); if (!TextUtils.isEmpty(setupActivity)) { source.setupActivity = ComponentName .unflattenFromString(ri.serviceInfo.packageName + "/" + setupActivity); } source.color = metaData.getInt("color", source.color); try { float[] hsv = new float[3]; Color.colorToHSV(source.color, hsv); boolean adjust = false; if (hsv[2] < 0.8f) { hsv[2] = 0.8f; adjust = true; } if (hsv[1] > 0.4f) { hsv[1] = 0.4f; adjust = true; } if (adjust) { source.color = Color.HSVToColor(hsv); } if (Color.alpha(source.color) != 255) { source.color = Color.argb(255, Color.red(source.color), Color.green(source.color), Color.blue(source.color)); } } catch (IllegalArgumentException ignored) { } } mSources.add(source); } final String appPackage = getContext().getPackageName(); Collections.sort(mSources, new Comparator<Source>() { @Override public int compare(Source s1, Source s2) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { boolean target1IsO = s1.targetSdkVersion >= Build.VERSION_CODES.O; boolean target2IsO = s2.targetSdkVersion >= Build.VERSION_CODES.O; if (target1IsO && !target2IsO) { return 1; } else if (!target1IsO && target2IsO) { return -1; } } String pn1 = s1.componentName.getPackageName(); String pn2 = s2.componentName.getPackageName(); if (!pn1.equals(pn2)) { if (appPackage.equals(pn1)) { return -1; } else if (appPackage.equals(pn2)) { return 1; } } return s1.label.compareTo(s2.label); } }); redrawSources(); }
From source file:git.egatuts.nxtremotecontroller.activity.ControllerActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.setActiveTheme(super.getPreferenceTheme()); super.setContentView(R.layout.controller_layout); toolbar = (Toolbar) this.findViewById(R.id.toolbar); super.setSupportToolbar(); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override/*from www.j a v a 2 s .co m*/ public void onClick(View v) { ControllerActivity.this.onBackPressed(); } }); /* * We get the device from the extra data of the intent. */ this.device = this.getIntent().getParcelableExtra("device"); /* * We create the final variables we will use in the listeners, etc. */ final ControllerActivity self = this; final GlobalUtils utils = this.getGlobalUtils(); /* * We create the AlertDialog.Builder we will show to ask the user to reconnect with the device. */ this.builder = utils .createAlertDialog(utils.getStringResource(R.string.connecting_reconnect_title), utils.format(R.string.connecting_reconnect_message, this.device.getName())) .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { self.finish(); } }).setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { self.resume(); } }); /* * Now we define the progress dialog we will show while we are connecting with the device. * When the progress dialog has been cancelled it means the connection process has been cancelled. * But on dismiss we have to check if the connection failed or it succeed. */ this.progressDialog = this.getLongProgressDialog(); this.progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { self.aborted = true; utils.showToast(R.string.connecting_aborted); self.connector.closeConnectThread(); self.finish(); } }); /* * Now we declare the handler that will handle (so obviously) the messages * sent by the threads that are in the background connecting with the device. */ this.handler = new Handler() { @Override public void handleMessage(Message msg) { if ((self.connector.getConnectThread() == null || self.aborted) && self.connector.getConnectedThread() == null) { return; } int category = msg.what; int state; int error; if (category == NXTConnector.WHAT_CHANGE_STATE) { progressDialog.show(); state = msg.arg1; error = msg.arg2; if (NXTConnector.isPreparingConnection(state)) { progressDialog.setText(R.string.connecting_preparing_connection); } else if (NXTConnector.isCreatingSocket(state)) { progressDialog.setText(R.string.connecting_creating_socket); } else if (NXTConnector.isConnecting(state)) { progressDialog.setText(R.string.connecting_connecting); } else if (NXTConnector.isConnected(state)) { progressDialog.dismiss(); utils.showToast(R.string.connecting_connected, device.getName()); self.connected(); } } else if (category == NXTConnector.WHAT_ERROR_ENCOUNTERED) { progressDialog.dismiss(); self.connector.closeAllThreads(); error = msg.arg1; state = msg.arg2; boolean notReconnect = false; if (NXTConnector.connectionClosed(state, error)) { utils.showToast(R.string.connecting_connection_closed); notReconnect = true; ControllerActivity.this.finish(); } else if (NXTConnector.connectionLost(state, error)) { utils.showToast(R.string.connecting_connection_lost); if (!self.connector.getBluetoothUtils().isEnabled()) { notReconnect = true; ControllerActivity.this.finish(); } } else if (NXTConnector.connectionSocketFailed(state, error)) { utils.showToast(R.string.connecting_socket_error); } else if (NXTConnector.connectionRequestFailed(state, error)) { utils.showToast(R.string.connecting_request_failed); } else if (NXTConnector.connectionUnexpectedFailed(state, error)) { utils.showToast(R.string.connecting_unexpected_error); } if (!notReconnect) { self.builder.show(); } } } }; /* * Now we create the connector with the device and the handler * which we will use to connect and send messages to the robot. */ this.connector = new NXTConnector(this, this.device, this.handler); /* * We set the title with the device name. */ String title = utils.getStringResource(R.string.controller_window_title); this.setTitle(title + this.device.getName()); /* * We set the colors we will use with the drawables used in the tabs. */ final int underlineColor = utils.getAttribute(R.attr.toolbar_color); final int backgroundColor = utils.getAttribute(R.attr.toolbar_background); final int lightBackgroundColor = GlobalUtils.mixColors(backgroundColor, 0x55FFFFFF); /* * Now we create the drawables used in all the states of the tabs and then we assign * them to a StateListDrawable to add it to the tabs. */ ShapeDrawable.ShaderFactory tabSelectedFactory = new ShapeDrawable.ShaderFactory() { @Override public Shader resize(int width, int height) { return new LinearGradient(0, 0, /* Origin of the background (top left corner) */ 0, height, /* End of the background (bottom left corner) */ new int[] { backgroundColor, backgroundColor, /* The first gradient doesn't change color so it's like a rectangle shape */ underlineColor, underlineColor /* The same for the second one */ }, new float[] { 0, 51f / 55f, /* The first background covers 51dp out of 55dp */ 51f / 55f, 1 /* And the second one takes the rest of the space */ }, Shader.TileMode.REPEAT /* The repeat mode doesn't mind but this would look prettier in case of error */ ); } }; PaintDrawable tabSel = new PaintDrawable(); tabSel.setShape(new RectShape()); tabSel.setShaderFactory(tabSelectedFactory); ShapeDrawable.ShaderFactory tabSelectedAndPressedFactory = new ShapeDrawable.ShaderFactory() { @Override public Shader resize(int width, int height) { return new LinearGradient(0, 0, /* Origin of the background (top left corner) */ 0, height, /* End of the background (bottom left corner) */ new int[] { lightBackgroundColor, lightBackgroundColor, /* The first gradient doesn't change color so it's like a rectangle shape */ underlineColor, underlineColor /* The same for the second one */ }, new float[] { 0, 51f / 55f, /* The first background covers 51dp out of 55dp */ 51f / 55f, 1 /* And the second one takes the rest of the space */ }, Shader.TileMode.REPEAT /* The repeat mode doesn't mind but this would look prettier in case of error */ ); } }; PaintDrawable tabSelAndPress = new PaintDrawable(); tabSelAndPress.setShape(new RectShape()); tabSelAndPress.setShaderFactory(tabSelectedAndPressedFactory); /* * Now we create the states lists for the drawables and the colors. */ StateListDrawable drawableList = new StateListDrawable(); drawableList.addState(new int[] { -android.R.attr.state_selected, android.R.attr.state_pressed }, new ColorDrawable(lightBackgroundColor)); drawableList.addState(new int[] { -android.R.attr.state_selected, android.R.attr.state_pressed, android.R.attr.state_focused }, new ColorDrawable(lightBackgroundColor)); drawableList.addState(new int[] { android.R.attr.state_selected, -android.R.attr.state_pressed }, tabSel); drawableList.addState(new int[] { android.R.attr.state_selected, -android.R.attr.state_pressed, -android.R.attr.state_focused }, tabSel); drawableList.addState(new int[] { android.R.attr.state_selected, android.R.attr.state_pressed }, tabSelAndPress); drawableList.addState(new int[] { android.R.attr.state_selected, android.R.attr.state_pressed, android.R.attr.state_focused }, tabSelAndPress); drawableList.addState(new int[] {}, new ColorDrawable(backgroundColor)); int darkColor = utils.getAttribute(R.attr.toolbar_color); int lightColor = Color.argb(0xAA, Color.red(darkColor), Color.green(darkColor), Color.blue(darkColor)); int[][] states = new int[][] { new int[] { -android.R.attr.state_selected, android.R.attr.state_pressed }, new int[] { -android.R.attr.state_selected, android.R.attr.state_pressed, android.R.attr.state_focused }, new int[] { android.R.attr.state_selected, -android.R.attr.state_pressed }, new int[] { android.R.attr.state_selected, -android.R.attr.state_pressed, -android.R.attr.state_focused }, new int[] { android.R.attr.state_selected, android.R.attr.state_pressed }, new int[] { android.R.attr.state_selected, android.R.attr.state_pressed, android.R.attr.state_focused }, new int[] { -android.R.attr.state_selected, -android.R.attr.state_pressed, -android.R.attr.state_focused }, new int[] {} }; int[] colors = new int[] { lightColor, /* Text color when pressed and not selected */ lightColor, /* Text color when pressed (with focused fallback) */ darkColor, /* Text color when selected and not pressed */ darkColor, /* Text color when selected and not pressed (with focused fallback) */ darkColor, /* Text color when selected and pressed */ darkColor, /* Text color when selected and pressed (with focused fallback) */ lightColor, /* Normal color when not pressed, selected or focused */ lightColor /* Default text color */ }; ColorStateList colorList = new ColorStateList(states, colors); /* * We assign the drawable and the list to the activity instance to be accessible everywhere. */ this.tabSelected = tabSel; this.tabSelectedAndPressed = tabSelAndPress; this.tabDrawableList = drawableList; this.tabColorList = colorList; /* * Now we setup the tab host and add the tabs to the view. */ this.tabHost = (FragmentTabHost) this.findViewById(R.id.tabhost); this.tabHost.setup(this, super.fragmentManager, R.id.tabcontent); this.tabHost.getTabWidget().setDividerDrawable(null); this.addTab(this.createTabView(R.layout.controller_tab, R.string.controller_tab_local_title), R.string.controller_tab_local_spec, LocalControllerFragment.class); this.addTab(this.createTabView(R.layout.controller_tab, R.string.controller_tab_online_title), R.string.controller_tab_online_spec, OnlineControllerFragment.class); }
From source file:com.bookkos.bircle.CaptureActivity.java
@Override public void onCreate(Bundle icicle) { super.onCreate(icicle); _context = getApplicationContext();/* w w w . j a va 2s. c o m*/ _activity = this; currentTime = new Time("Asia/Tokyo"); // exceptionHandler = new ExceptionHandler(_context); // Thread.setDefaultUncaughtExceptionHandler(exceptionHandler); // sharedPreference???, user_id?group_id?registration_id?? getUserData(); Window window = getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // ?? WindowManager window_manager = getWindowManager(); Display display = window_manager.getDefaultDisplay(); Point point = new Point(); display.getSize(point); displayWidth = point.x; displayHeight = point.y; displayInch = getInch(); // ??4??????? textSize = 17 * (displayInch / 4); actionBar = getActionBar(); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE, ActionBar.DISPLAY_USE_LOGO); actionBar.setDisplayShowTitleEnabled(true); actionBar.setDisplayUseLogoEnabled(false); actionBar.setDisplayShowHomeEnabled(false); actionBar.setDisplayHomeAsUpEnabled(false); String title_text = ""; subGroupText = ""; groupText = groupName; if (displayInch < 4.7) { title_text = "<small><small><small>??: </small></small></small>"; resizeTitleSizeTooSmall(); } else if (displayInch >= 4.7 && displayInch < 5.5) { title_text = "<small><small>??: </small></small>"; resizeTitleSizeSmall(); } else if (displayInch >= 5.5 && displayInch < 6.5) { title_text = "<small>??: </small>"; resizeTitleSizeMiddle(); } else if (displayInch >= 6.5 && displayInch < 8) { title_text = "<small>??: </small>"; resizeTitleSizeLarge(); } else { title_text = "??: "; } String modify_group_text = title_text + "<font color=#FF0000>" + groupName + "</font>"; actionBar.setTitle(Html.fromHtml(modify_group_text)); Resources resources = _context.getResources(); int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android"); titleBarHeight = resources.getDimensionPixelSize(resourceId); setContentView(R.layout.capture); returnBorrowHelpView = (ImageView) findViewById(R.id.return_borrow_help_view); returnBorrowHelpView.setImageResource(R.drawable.return_borrow_help); returnBorrowHelpView.setTranslationY(displayHeight / 5 + titleBarHeight); returnBorrowHelpView.setLayoutParams(new FrameLayout.LayoutParams(displayWidth, displayHeight / 5 + titleBarHeight, Gravity.BOTTOM | Gravity.CENTER)); registHelpView = (ImageView) findViewById(R.id.regist_help_view); registHelpView.setImageResource(R.drawable.regist_help); registHelpView.setTranslationY(displayHeight / 5 + titleBarHeight); registHelpView.setLayoutParams(new FrameLayout.LayoutParams(displayWidth, displayHeight / 5 + titleBarHeight, Gravity.BOTTOM | Gravity.CENTER)); registHelpView.setVisibility(View.GONE); leftDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); leftDrawer = (ListView) findViewById(R.id.left_drawer); textView = (TextView) findViewById(R.id.textView); modeText = (TextView) findViewById(R.id.mode_text); modeText.setTextColor(Color.rgb(56, 234, 123)); modeText.setTextSize(textSize); modeText.setTypeface(Typeface.SERIF.MONOSPACE, Typeface.BOLD); strokeColor = Color.rgb(56, 234, 123); borrowReturnButton = (Button) findViewById(R.id.borrowReturnButton); registButton = (Button) findViewById(R.id.registButton); returnHistoryButton = (Button) findViewById(R.id.return_history_button); helpViewButton = (Button) findViewById(R.id.help_view_button); registSelectShelfRelativeLayout = (RelativeLayout) findViewById(R.id.regist_select_shelf_relative_layout); textViewLinearLayout = (LinearLayout) findViewById(R.id.text_view_linear_layout); buttonLinearLayout = (LinearLayout) findViewById(R.id.button_linear_layout); listViewLinearLayout = (LinearLayout) findViewById(R.id.list_view_linear_layout); decisionButton = (Button) findViewById(R.id.decision_button); cancelButton = (Button) findViewById(R.id.cancel_button); shelfListView = (ListView) findViewById(R.id.shelf_list_view); tempTextView = (TextView) findViewById(R.id.temp_text_view); // bookListViewAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1); bookListViewAdapter = new BookListViewAdapter(_context, R.layout.book_list_row, this); bookRegistRelativeLayout = (RelativeLayout) findViewById(R.id.book_regist_relative_layout); bookRegistLinearLayout = (LinearLayout) findViewById(R.id.book_regist_linear_layout); bookRegistListViewLinearLayout = (LinearLayout) findViewById(R.id.book_regist_list_view_linear_layout); bookRegistListView = (ListView) findViewById(R.id.book_regist_list_view); bookRegistTextView = (TextView) findViewById(R.id.book_regist_text_view); bookRegistCancelButton = (Button) findViewById(R.id.book_regist_cancel_button); registFlag = 0; int borrowReturnButton_width = displayWidth / 5 * 2; int borrowReturnButton_height = displayHeight / 10; int borrowReturnButton_x = ((displayWidth / 2) - borrowReturnButton_width) / 2; int borrowReturnButton_y = displayHeight / 2 + titleBarHeight; borrowReturnButton.setTranslationX(borrowReturnButton_x); borrowReturnButton.setTranslationY(borrowReturnButton_y); borrowReturnButton .setLayoutParams(new FrameLayout.LayoutParams(borrowReturnButton_width, borrowReturnButton_height)); borrowReturnButton.setBackgroundColor(Color.rgb(56, 234, 123)); borrowReturnButton.setText("??\n"); borrowReturnButton.setTextSize(textSize * 7 / 10); borrowReturnButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { arrayList.clear(); registFlag = 0; borrowReturnButton.setText("??\n"); borrowReturnButton.setEnabled(false); borrowReturnButton.setTextColor(Color.WHITE); borrowReturnButton.setBackgroundColor(Color.rgb(56, 234, 123)); registButton.setText("?\n??"); registButton.setEnabled(true); registButton.setTextColor(Color.GRAY); registButton.setBackgroundColor(Color.argb(170, 21, 38, 45)); modeText.setText("??"); modeText.setTextColor(Color.rgb(56, 234, 123)); returnBorrowHelpView.setVisibility(View.VISIBLE); registHelpView.setVisibility(View.GONE); strokeColor = Color.rgb(56, 234, 123); } }); int registButton_width = displayWidth / 5 * 2; int registButton_height = displayHeight / 10; int registButton_x = (displayWidth / 2) + ((displayWidth / 2) - registButton_width) / 2; int registButton_y = displayHeight / 2 + titleBarHeight; registButton.setTranslationX(registButton_x); registButton.setTranslationY(registButton_y); registButton.setLayoutParams(new FrameLayout.LayoutParams(registButton_width, registButton_height)); registButton.setBackgroundColor(Color.argb(170, 21, 38, 45)); registButton.setTextColor(Color.GRAY); registButton.setTextSize(textSize * 7 / 10); registButton.setText("?\n??"); registButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { arrayList.clear(); registFlag = 1; borrowReturnButton.setText("??\n??"); borrowReturnButton.setEnabled(true); borrowReturnButton.setTextColor(Color.GRAY); borrowReturnButton.setBackgroundColor(Color.argb(170, 9, 54, 16)); registButton.setText("?\n"); registButton.setEnabled(false); registButton.setTextColor(Color.WHITE); registButton.setBackgroundColor(Color.rgb(62, 162, 229)); modeText.setText("?"); modeText.setTextColor(Color.rgb(62, 162, 229)); returnBorrowHelpView.setVisibility(View.GONE); registHelpView.setVisibility(View.VISIBLE); strokeColor = Color.rgb(62, 162, 229); } }); returnHistoryButton.setText("????"); returnHistoryButton.setTextSize(textSize * 7 / 10); returnHistoryButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { leftDrawerLayout.openDrawer(Gravity.RIGHT); // animateTranslationY(bookRegistRelativeLayout, displayHeight, displayHeight - displayHeight / 4 - titleBarHeight); } }); getReturnHistory(); getCurrentTime(); setHelpView(); setScanUnregisterBookView(); setBookRegistView(); arrayList = new ArrayList<String>(); tempRegistIsbn = ""; initBookRegistUrl = book_register_url + "?user_id=" + userId + "&group_id=" + groupId; initLendRegistUrl = lend_register_url + "?user_id=" + userId + "&group_id=" + groupId; initTemporaryLendRegistUrl = temporary_lend_register_url + "?user_id=" + userId + "&group_id=" + groupId; initCatalogRegistUrl = catalog_register_url + "?group_id=" + groupId + "&book_code="; initManuallyCatalogRegistUrl = manually_catalog_register_url + "?group_id=" + groupId + "&book_code="; getStatusUrl = get_status_url + "?group_id=" + groupId + "&user_id=" + userId; hasSurface = false; inactivityTimer = new InactivityTimer(this); bircleBeepManager = new BircleBeepManager(this); ambientLightManager = new AmbientLightManager(this); PreferenceManager.setDefaultValues(this, R.xml.preferences, false); toastText = ""; }
From source file:com.ryan.ryanreader.fragments.CommentListingFragment.java
private void makeFirstRequest(final Context context) { final RedditAccount user = RedditAccountManager.getInstance(context).getDefaultAccount(); final CacheManager cm = CacheManager.getInstance(context); // TODO parameterise limit request = new CacheRequest(url, user, session, Constants.Priority.API_COMMENT_LIST, 0, downloadType, Constants.FileType.COMMENT_LIST, true, true, false, context) { @Override//from ww w .j a va 2s . com protected void onDownloadNecessary() { new Handler(Looper.getMainLooper()).post(new Runnable() { public void run() { listFooter.addView(loadingView); adapter.notifyDataSetChanged(); } }); } @Override protected void onDownloadStarted() { loadingView.setIndeterminate(context.getString(R.string.download_connecting)); } @Override protected void onCallbackException(final Throwable t) { request = null; BugReportActivity.handleGlobalError(context, t); } @Override protected void onFailure(final RequestFailureType type, final Throwable t, final StatusLine status, final String readableMessage) { request = null; if (!isAdded()) return; if (loadingView != null) loadingView.setDoneNoAnim(R.string.download_failed); final RRError error = General.getGeneralErrorForFailure(context, type, t, status); new Handler(Looper.getMainLooper()).post(new Runnable() { public void run() { notifications.addView(new ErrorView(getSupportActivity(), error)); } }); } @Override protected void onProgress(final long bytesRead, final long totalBytes) { } @Override protected void onSuccess(final CacheManager.ReadableCacheFile cacheFile, final long timestamp, final UUID session, final boolean fromCache, final String mimetype) { request = null; } @Override public void onJsonParseStarted(final JsonValue value, final long timestamp, final UUID session, final boolean fromCache) { if (isAdded() && loadingView != null) loadingView.setIndeterminate("Downloading..."); // TODO pref (currently 10 mins) // TODO xml if (fromCache && RRTime.since(timestamp) > 10 * 60 * 1000) { new Handler(Looper.getMainLooper()).post(new Runnable() { public void run() { if (isDetached()) return; final TextView cacheNotif = new TextView(context); cacheNotif.setText(context.getString(R.string.listing_cached) + " " + RRTime.formatDateTime(timestamp, context)); final int paddingPx = General.dpToPixels(context, 6); final int sidePaddingPx = General.dpToPixels(context, 10); cacheNotif.setPadding(sidePaddingPx, paddingPx, sidePaddingPx, paddingPx); cacheNotif.setTextSize(13f); listHeaderNotifications.addView(cacheNotif); adapter.notifyDataSetChanged(); } }); } ((SessionChangeListener) getSupportActivity()).onSessionChanged(session, SessionChangeListener.SessionChangeType.COMMENTS, timestamp); // TODO {"error": 403} is received for unauthorized subreddits try { // Download main post if (value.getType() == JsonValue.Type.ARRAY) { // lol, reddit api final JsonBufferedArray root = value.asArray(); final JsonBufferedObject thing = root.get(0).asObject(); final JsonBufferedObject listing = thing.getObject("data"); final JsonBufferedArray postContainer = listing.getArray("children"); final RedditThing postThing = postContainer.getObject(0, RedditThing.class); final RedditPost post = postThing.asPost(); // TODO show upvote/downvote/etc buttons final RedditSubreddit parentSubreddit = new RedditSubreddit("/r/" + post.subreddit, post.subreddit, false); CommentListingFragment.this.post = new RedditPreparedPost(context, cm, 0, post, timestamp, true, parentSubreddit, false, false, false, user); final ViewGroup selfText; if (post.is_self && post.selftext != null && post.selftext.trim().length() > 0) { selfText = RedditCommentTextParser.parse(StringEscapeUtils.unescapeHtml4(post.selftext)) .generate(context, 14f * commentFontScale, null, new ActiveTextView.OnLinkClickedListener() { public void onClickUrl(String url) { if (url != null) LinkHandler.onLinkClicked(getSupportActivity(), url, false); } public void onClickText(Object attachment) { } }, CommentListingFragment.this.post); } else { selfText = null; } new Handler(Looper.getMainLooper()).post(new Runnable() { public void run() { final RedditPostHeaderView postHeader = new RedditPostHeaderView( getSupportActivity(), CommentListingFragment.this.post, CommentListingFragment.this); listHeaderPost.addView(postHeader); if (selfText != null) { selfText.setFocusable(false); selfText.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS); final int paddingPx = General.dpToPixels(context, 10); listHeaderSelftext.addView(selfText); listHeaderSelftext.setPadding(paddingPx, paddingPx, paddingPx, paddingPx); listHeaderNotifications.setBackgroundColor(Color.argb(35, 128, 128, 128)); } if (!General.isTablet(context, PreferenceManager.getDefaultSharedPreferences(context))) { getSupportActivity().getSupportActionBar().setTitle(post.title); } } }); } // Download comments final JsonBufferedObject thing; if (value.getType() == JsonValue.Type.ARRAY) { thing = value.asArray().get(1).asObject(); } else { thing = value.asObject(); } final JsonBufferedObject listing = thing.getObject("data"); final JsonBufferedArray topLevelComments = listing.getArray("children"); final HashSet<String> needsChanging = RedditChangeDataManager.getInstance(context) .getChangedForParent(parentPostIdAndType, user); for (final JsonValue commentThingValue : topLevelComments) { buildComments(commentThingValue, null, timestamp, needsChanging); } commentHandler.sendMessage(General.handlerMessage(0, buffer)); } catch (Throwable t) { notifyFailure(RequestFailureType.PARSE, t, null, "Parse failure"); return; } if (isAdded() && loadingView != null) loadingView.setDoneNoAnim(R.string.download_done); } private ArrayList<RedditPreparedComment> buffer = new ArrayList<RedditPreparedComment>(); private void buildComments(final JsonValue value, final RedditPreparedComment parent, final long timestamp, final HashSet<String> needsChanging) throws IOException, InterruptedException, IllegalAccessException, java.lang.InstantiationException, NoSuchMethodException, InvocationTargetException { final RedditThing commentThing = value.asObject(RedditThing.class); if (commentThing.getKind() != RedditThing.Kind.COMMENT) return; final RedditComment comment = commentThing.asComment(); final RedditPreparedComment preparedComment = new RedditPreparedComment(context, comment, parent, timestamp, needsChanging.contains(comment.name), post, user, headerItems); after = preparedComment.idAndType; buffer.add(preparedComment); if (buffer.size() >= 40) { commentHandler.sendMessage(General.handlerMessage(0, buffer)); buffer = new ArrayList<RedditPreparedComment>(); } if (comment.replies.getType() == JsonValue.Type.OBJECT) { final JsonBufferedObject replies = comment.replies.asObject(); final JsonBufferedArray children = replies.getObject("data").getArray("children"); for (final JsonValue v : children) { buildComments(v, preparedComment, timestamp, needsChanging); } } } }; cm.makeRequest(request); }
From source file:com.skytree.epubtest.BookViewActivity.java
public void makeLayout() { // make fonts this.makeFonts(); // clear the existing themes. themes.clear();/* w w w .j av a2s .c om*/ // add themes // String name,int foregroundColor,int backgroundColor,int controlColor,int controlHighlightColor,int seekBarColor,int seekThumbColor,int selectorColor,int selectionColor,String portraitName,String landscapeName,String doublePagedName,int bookmarkId themes.add(new Theme("white", Color.BLACK, 0xffffffff, Color.argb(240, 94, 61, 35), Color.LTGRAY, Color.argb(240, 94, 61, 35), Color.argb(120, 160, 124, 95), Color.DKGRAY, 0x22222222, "Phone-Portrait-White.png", "Phone-Landscape-White.png", "Phone-Landscape-Double-White.png", R.drawable.bookmark2x)); themes.add(new Theme("brown", Color.BLACK, 0xffece3c7, Color.argb(240, 94, 61, 35), Color.argb(255, 255, 255, 255), Color.argb(240, 94, 61, 35), Color.argb(120, 160, 124, 95), Color.DKGRAY, 0x22222222, "Phone-Portrait-Brown.png", "Phone-Landscape-Brown.png", "Phone-Landscape-Double-Brown.png", R.drawable.bookmark2x)); themes.add(new Theme("black", Color.LTGRAY, 0xff323230, Color.LTGRAY, Color.LTGRAY, Color.LTGRAY, Color.LTGRAY, Color.LTGRAY, 0x77777777, null, null, "Phone-Landscape-Double-Black.png", R.drawable.bookmarkgray2x)); themes.add(new Theme("Leaf", 0xFF1F7F0E, 0xffF8F7EA, 0xFF186D08, Color.LTGRAY, 0xFF186D08, 0xFF186D08, Color.DKGRAY, 0x22222222, null, null, null, R.drawable.bookmarkgray2x)); themes.add(new Theme("", 0xFFA13A0A, 0xFFF6DFD9, 0xFFA13A0A, 0xFFDC4F0E, 0xFFA13A0A, 0xFFA13A0A, Color.DKGRAY, 0x22222222, null, null, null, R.drawable.bookmarkgray2x)); this.setBrightness((float) setting.brightness); // create highlights object to contains highlights of this book. highlights = new Highlights(); Bundle bundle = getIntent().getExtras(); fileName = bundle.getString("BOOKNAME"); author = bundle.getString("AUTHOR"); title = bundle.getString("TITLE"); bookCode = bundle.getInt("BOOKCODE"); if (pagePositionInBook == -1) pagePositionInBook = bundle.getDouble("POSITION"); themeIndex = setting.theme; this.isGlobalPagination = bundle.getBoolean("GLOBALPAGINATION"); this.isRTL = bundle.getBoolean("RTL"); this.isVerticalWriting = bundle.getBoolean("VERTICALWRITING"); this.isDoublePagedForLandscape = bundle.getBoolean("DOUBLEPAGED"); // if (this.isRTL) this.isDoublePagedForLandscape = false; // In RTL mode, SDK does not support double paged. ePubView = new RelativeLayout(this); RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT); ePubView.setLayoutParams(rlp); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); // width,height if (this.getOSVersion() >= 11) { rv = new ReflowableControl(this); // in case that device supports transparent webkit, the background image under the content can be shown. in some devices, content may be overlapped. } else { rv = new ReflowableControl(this, getCurrentTheme().backgroundColor); // in case that device can not support transparent webkit, the background color will be set in one color. } // if false highlight will be drawed on the back of text - this is default. // for the very old devices of which GPU does not support transparent webView background, set the value to true. rv.setDrawingHighlightOnFront(false); // set the bookCode to identify the book file. rv.bookCode = this.bookCode; // set bitmaps for engine. rv.setPagesStackImage(this.getBitmap("PagesStack.png")); rv.setPagesCenterImage(this.getBitmap("PagesCenter.png")); // for epub3 which has page-progression-direction="rtl", rv.isRTL() will return true. // for old RTL epub which does not have <spine toc="ncx" page-progression-direction="rtl"> in opf file. // you can enforce RTL mode. /* // delay times for proper operations. // !! DO NOT SET these values if there's no issue on your epub reader. !! // !! if delayTime is decresed, performance will be increase // !! if delayTime is set to too low value, a lot of problem can be occurred. // bringDelayTime(default 500 ms) is for curlView and mainView transition - if the value is too short, blink may happen. rv.setBringDelayTime(500); // reloadDelayTime(default 100) is used for delay before reload (eg. changeFont, loadChapter or etc) rv.setReloadDelayTime(100); // reloadDelayTimeForRotation(default 1000) is used for delay before rotation rv.setReloadDelayTimeForRotation(1000); // retotaionDelayTime(default 1500) is used for delay after rotation. rv.setRotationDelayTime(1500); // finalDelayTime(default 500) is used for the delay after loading chapter. rv.setFinalDelayTime(500); // rotationFactor affects the delayTime before Rotation. default value 1.0f rv.setRotationFactor(1.0f); // If recalcDelayTime is too short, setContentBackground function failed to work properly. rv.setRecalcDelayTime(2500); */ // set the max width or height for background. rv.setMaxSizeForBackground(1024); // rv.setBaseDirectory(SkySetting.getStorageDirectory() + "/books"); // rv.setBookName(fileName); // set the file path of epub to open // Be sure that the file exists before setting. rv.setBookPath(SkySetting.getStorageDirectory() + "/books/" + fileName); // if true, double pages will be displayed on landscape mode. rv.setDoublePagedForLandscape(this.isDoublePagedForLandscape); // set the initial font style for book. rv.setFont(setting.fontName, this.getRealFontSize(setting.fontSize)); // set the initial line space for book. rv.setLineSpacing(this.getRealLineSpace(setting.lineSpacing)); // the value is supposed to be percent(%). // set the horizontal gap(margin) on both left and right side of each page. rv.setHorizontalGapRatio(0.30); // set the vertical gap(margin) on both top and bottom side of each page. rv.setVerticalGapRatio(0.22); // set the HighlightListener to handle text highlighting. rv.setHighlightListener(new HighlightDelegate()); // set the PageMovedListener which is called whenever page is moved. rv.setPageMovedListener(new PageMovedDelegate()); // set the SelectionListener to handle text selection. rv.setSelectionListener(new SelectionDelegate()); // set the pagingListener which is called when GlobalPagination is true. this enables the calculation for the total number of pages in book, not in chapter. rv.setPagingListener(new PagingDelegate()); // set the searchListener to search keyword. rv.setSearchListener(new SearchDelegate()); // set the stateListener to monitor the state of sdk engine. rv.setStateListener(new StateDelegate()); // set the clickListener which is called when user clicks rv.setClickListener(new ClickDelegate()); // set the bookmarkListener to toggle bookmark rv.setBookmarkListener(new BookmarkDelegate()); // set the scriptListener to set custom javascript. rv.setScriptListener(new ScriptDelegate()); // enable/disable scroll mode rv.setScrollMode(false); // for some anroid device, when rendering issues are occurred, use "useSoftwareLayer" // rv.useSoftwareLayer(); // In search keyword, if true, sdk will return search result with the full information such as position, pageIndex. rv.setFullSearch(true); // if true, sdk will return raw text for search result, highlight text or body text without character escaping. rv.setRawTextRequired(false); // if true, sdk will read the content of book directry from file system, not via Internal server. // rv.setDirectRead(true); // If you want to make your own provider, please look into EpubProvider.java in Advanced demo. // EpubProvider epubProvider = new EpubProvider(); // rv.setContentProvider(epubProvider); // SkyProvider is the default ContentProvider which is presented with SDK. // SkyProvider can read the content of epub file without unzipping. // SkyProvider is also fully integrated with SkyDRM solution. SkyProvider skyProvider = new SkyProvider(); skyProvider.setKeyListener(new KeyDelegate()); rv.setContentProvider(skyProvider); // set the start positon to open the book. rv.setStartPositionInBook(pagePositionInBook); // DO NOT USE BELOW, if true , sdk will use DOM to highlight text. // rv.useDOMForHighlight(false); // if true, globalPagination will be activated. // this enables the calculation of page number based on entire book ,not on each chapter. // this globalPagination consumes huge computing power. // AVOID GLOBAL PAGINATION FOR LOW SPEC DEVICES. rv.setGlobalPagination(this.isGlobalPagination); // set the navigation area on both left and right side to go to the previous or next page when the area is clicked. rv.setNavigationAreaWidthRatio(0.1f); // both left and right side. // set the device locked to prevent Rotation. rv.setRotationLocked(setting.lockRotation); isRotationLocked = setting.lockRotation; // set the mediaOverlayListener for MediaOverlay. rv.setMediaOverlayListener(new MediaOverlayDelegate()); // set the audio playing based on Sequence. rv.setSequenceBasedForMediaOverlay(false); params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE); params.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE); params.width = LayoutParams.MATCH_PARENT; params.height = LayoutParams.MATCH_PARENT; rv.setLayoutParams(params); this.applyThemeToRV(themeIndex); if (this.isFullScreenForNexus && SkyUtility.isNexus() && Build.VERSION.SDK_INT >= 19) { rv.setImmersiveMode(true); } // If you want to get the license key for commercial use, please email us (skytree21@gmail.com). // Without the license key, watermark message will be shown in background. rv.setLicenseKey("a99b-3914-a63b-8ecb"); // set PageTransition Effect int transitionType = bundle.getInt("transitionType"); if (transitionType == 0) { rv.setPageTransition(PageTransition.None); } else if (transitionType == 1) { rv.setPageTransition(PageTransition.Slide); } else if (transitionType == 2) { rv.setPageTransition(PageTransition.Curl); } // setCurlQuality effects the image quality when tuning page in Curl Transition Mode. // If "Out of Memory" occurs in high resolution devices with big screen, // this value should be decreased like 0.25f or below. if (this.getMaxSize() > 1280) { rv.setCurlQuality(0.5f); } // set the color of text selector. rv.setSelectorColor(getCurrentTheme().selectorColor); // set the color of text selection area. rv.setSelectionColor(getCurrentTheme().selectionColor); // setCustomDrawHighlight & setCustomDrawCaret work only if SDK >= 11 // if true, sdk will ask you how to draw the highlighted text rv.setCustomDrawHighlight(true); // if true, sdk will require you to draw the custom selector. rv.setCustomDrawCaret(true); rv.setFontUnit("px"); rv.setFingerTractionForSlide(true); rv.setVideoListener(new VideoDelegate()); // make engine not to send any event to iframe // if iframe clicked, onIFrameClicked will be fired with source of iframe // By Using that source of iframe, you can load the content of iframe in your own webView or another browser. rv.setSendingEventsToIFrameEnabled(false); // make engine send any event to video(tag) or not // if video tag is clicked, onVideoClicked will be fired with source of iframe // By Using that source of video, you can load the content of video in your own media controller or another browser. rv.setSendingEventsToVideoEnabled(true); // make engine send any event to video(tag) or not // if video tag is clicked, onVideoClicked will be fired with source of iframe // By Using that source of video, you can load the content of video in your own media controller or another browser. rv.setSendingEventsToAudioEnabled(true); // if true, sdk will return the character offset from the chapter beginning , not from element index. // then startIndex, endIndex of highlight will be 0 (zero) rv.setGlobalOffset(true); // if true, sdk will return the text of each page in the PageInformation object which is passed in onPageMoved event. rv.setExtractText(true); ePubView.addView(rv); this.makeControls(); this.makeBoxes(); this.makeIndicator(); this.recalcFrames(); if (this.isRTL) { this.seekBar.setReversed(true); } setContentView(ePubView); this.isInitialized = true; }
From source file:com.android.launcher3.folder.FolderIcon.java
private void drawPreviewItem(Canvas canvas, PreviewItemDrawingParams params) { canvas.save();/*w w w . j av a 2s .co m*/ canvas.translate(params.transX, params.transY); canvas.scale(params.scale, params.scale); Drawable d = params.drawable; if (d != null) { mOldBounds.set(d.getBounds()); d.setBounds(0, 0, mIntrinsicIconSize, mIntrinsicIconSize); if (d instanceof FastBitmapDrawable) { FastBitmapDrawable fd = (FastBitmapDrawable) d; float oldBrightness = fd.getBrightness(); fd.setBrightness(params.overlayAlpha); d.draw(canvas); fd.setBrightness(oldBrightness); } else { d.setColorFilter(Color.argb((int) (params.overlayAlpha * 255), 255, 255, 255), PorterDuff.Mode.SRC_ATOP); d.draw(canvas); d.clearColorFilter(); } d.setBounds(mOldBounds); } canvas.restore(); }
From source file:de.madvertise.android.sdk.MadView.java
/** * Draw the ad background for a text banner * //from w w w .ja v a2 s . com * @param canvas * @param rectangle * @param backgroundColor * @param textColor */ private void drawTextBannerBackground(Canvas canvas, Rect rectangle, int backgroundColor, int shineColor) { Paint paint = new Paint(); paint.setColor(backgroundColor); paint.setAntiAlias(true); canvas.drawRect(rectangle, paint); int upperColor = Color.argb(GRADIENT_TOP_ALPHA, Color.red(shineColor), Color.green(shineColor), Color.blue(shineColor)); int[] gradientColors = { upperColor, shineColor }; GradientDrawable gradientDrawable = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, gradientColors); int stop = (int) (rectangle.height() * GRADIENT_STOP) + rectangle.top; gradientDrawable.setBounds(rectangle.left, rectangle.top, rectangle.right, stop); gradientDrawable.draw(canvas); Rect shadowRect = new Rect(rectangle.left, stop, rectangle.right, rectangle.bottom); Paint shadowPaint = new Paint(); shadowPaint.setColor(shineColor); canvas.drawRect(shadowRect, shadowPaint); }
From source file:org.lol.reddit.fragments.CommentListingFragment.java
@Override public void onCommentListingRequestPostDownloaded(final RedditPreparedPost post) { final Context context = getSupportActivity(); if (mPost == null) { mPost = post;//w w w. j a v a 2 s. c o m final RedditPostHeaderView postHeader = new RedditPostHeaderView(getSupportActivity(), CommentListingFragment.this.mPost); listHeaderPost.addView(postHeader); if (post.parsedSelfText != null) { final ViewGroup selfText = post.parsedSelfText.buildView(getSupportActivity(), null, 14f * commentFontScale, mShowLinkButtons); selfText.setFocusable(false); selfText.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS); final int paddingPx = General.dpToPixels(context, 10); listHeaderSelftext.addView(selfText); listHeaderSelftext.setPadding(paddingPx, paddingPx, paddingPx, paddingPx); listHeaderNotifications.setBackgroundColor(Color.argb(35, 128, 128, 128)); } if (!General.isTablet(context, PreferenceManager.getDefaultSharedPreferences(context))) { getSupportActivity().getSupportActionBar().setTitle(StringEscapeUtils.unescapeHtml4(post.title)); } } }
From source file:com.tiange.hz.wheelview.widget.WheelView.java
private void drawMask(Canvas canvas) { int center = getHeight() / 2; int offset = (int) (getItemHeight() / 2 * 1.2); /*int maskA = Color.alpha(wheelBackgroundColor); int maskR = Color.red(wheelBackgroundColor); int maskG = Color.green(wheelBackgroundColor); int maskB = Color.blue(wheelBackgroundColor);*/ int wheelUnSelectedMaskColor = Color.argb((int) (255 * wheelUnselectedMaskAlphaRate), 255, 255, 255); Paint paint = new Paint(); paint.setColor(wheelUnSelectedMaskColor); canvas.drawRect(0, 0, getWidth(), center - offset - 1, paint); canvas.drawRect(0, center + offset + 1, getWidth(), getHeight(), paint); }