List of usage examples for android.widget FrameLayout setBackgroundColor
@RemotableViewMethod public void setBackgroundColor(@ColorInt int color)
From source file:com.initialxy.cordova.themeablebrowser.ThemeableBrowser.java
/** * Display a new browser with the specified URL. * * @param url// ww w . j a va 2 s . co m * @param features * @return */ public String showWebPage(final String url, final Options features) { final CordovaWebView thatWebView = this.webView; // Create dialog in new thread Runnable runnable = new Runnable() { @SuppressLint("NewApi") public void run() { // Let's create the main dialog dialog = new ThemeableBrowserDialog(cordova.getActivity(), android.R.style.Theme_Black_NoTitleBar, features.hardwareback); if (!features.disableAnimation) { dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog; } dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setCancelable(true); dialog.setThemeableBrowser(getThemeableBrowser()); // Main container layout ViewGroup main = null; if (features.fullscreen) { main = new FrameLayout(cordova.getActivity()); } else { main = new LinearLayout(cordova.getActivity()); ((LinearLayout) main).setOrientation(LinearLayout.VERTICAL); } // Toolbar layout Toolbar toolbarDef = features.toolbar; FrameLayout toolbar = new FrameLayout(cordova.getActivity()); toolbar.setBackgroundColor(hexStringToColor( toolbarDef != null && toolbarDef.color != null ? toolbarDef.color : "#ffffffff")); toolbar.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, dpToPixels(toolbarDef != null ? toolbarDef.height : TOOLBAR_DEF_HEIGHT))); if (toolbarDef != null && (toolbarDef.image != null || toolbarDef.wwwImage != null)) { try { Drawable background = getImage(toolbarDef.image, toolbarDef.wwwImage, toolbarDef.wwwImageDensity); setBackground(toolbar, background); } catch (Resources.NotFoundException e) { emitError(ERR_LOADFAIL, String.format("Image for toolbar, %s, failed to load", toolbarDef.image)); } catch (IOException ioe) { emitError(ERR_LOADFAIL, String.format("Image for toolbar, %s, failed to load", toolbarDef.wwwImage)); } } // Left Button Container layout LinearLayout leftButtonContainer = new LinearLayout(cordova.getActivity()); FrameLayout.LayoutParams leftButtonContainerParams = new FrameLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); leftButtonContainerParams.gravity = Gravity.LEFT | Gravity.CENTER_VERTICAL; leftButtonContainer.setLayoutParams(leftButtonContainerParams); leftButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL); // Right Button Container layout LinearLayout rightButtonContainer = new LinearLayout(cordova.getActivity()); FrameLayout.LayoutParams rightButtonContainerParams = new FrameLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); rightButtonContainerParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL; rightButtonContainer.setLayoutParams(rightButtonContainerParams); rightButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL); // Edit Text Box edittext = new EditText(cordova.getActivity()); RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1); textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5); edittext.setLayoutParams(textLayoutParams); edittext.setSingleLine(true); edittext.setText(url); edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI); edittext.setImeOptions(EditorInfo.IME_ACTION_GO); edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE edittext.setOnKeyListener(new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { // If the event is a key-down event on the "enter" button if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { navigate(edittext.getText().toString()); return true; } return false; } }); // Back button final Button back = createButton(features.backButton, "back button", new View.OnClickListener() { public void onClick(View v) { emitButtonEvent(features.backButton, inAppWebView.getUrl()); if (features.backButtonCanClose && !canGoBack()) { closeDialog(); } else { goBack(); } } }); if (back != null) { back.setEnabled(features.backButtonCanClose); } // Forward button final Button forward = createButton(features.forwardButton, "forward button", new View.OnClickListener() { public void onClick(View v) { emitButtonEvent(features.forwardButton, inAppWebView.getUrl()); goForward(); } }); if (forward != null) { forward.setEnabled(false); } // Close/Done button Button close = createButton(features.closeButton, "close button", new View.OnClickListener() { public void onClick(View v) { emitButtonEvent(features.closeButton, inAppWebView.getUrl()); closeDialog(); } }); // Menu button Spinner menu = features.menu != null ? new MenuSpinner(cordova.getActivity()) : null; if (menu != null) { menu.setLayoutParams( new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); menu.setContentDescription("menu button"); setButtonImages(menu, features.menu, DISABLED_ALPHA); // We are not allowed to use onClickListener for Spinner, so we will use // onTouchListener as a fallback. menu.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP) { emitButtonEvent(features.menu, inAppWebView.getUrl()); } return false; } }); if (features.menu.items != null) { HideSelectedAdapter<EventLabel> adapter = new HideSelectedAdapter<EventLabel>( cordova.getActivity(), android.R.layout.simple_spinner_item, features.menu.items); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); menu.setAdapter(adapter); menu.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { if (inAppWebView != null && i < features.menu.items.length) { emitButtonEvent(features.menu.items[i], inAppWebView.getUrl(), i); } } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); } } // Title final TextView title = features.title != null ? new TextView(cordova.getActivity()) : null; final TextView subtitle = features.title != null ? new TextView(cordova.getActivity()) : null; if (title != null) { FrameLayout.LayoutParams titleParams = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.FILL_PARENT); titleParams.gravity = Gravity.CENTER; title.setLayoutParams(titleParams); title.setSingleLine(); title.setEllipsize(TextUtils.TruncateAt.END); title.setGravity(Gravity.CENTER | Gravity.TOP); title.setTextColor( hexStringToColor(features.title.color != null ? features.title.color : "#000000ff")); title.setTypeface(title.getTypeface(), Typeface.BOLD); title.setTextSize(TypedValue.COMPLEX_UNIT_PT, 8); FrameLayout.LayoutParams subtitleParams = new FrameLayout.LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.FILL_PARENT); titleParams.gravity = Gravity.CENTER; subtitle.setLayoutParams(subtitleParams); subtitle.setSingleLine(); subtitle.setEllipsize(TextUtils.TruncateAt.END); subtitle.setGravity(Gravity.CENTER | Gravity.BOTTOM); subtitle.setTextColor(hexStringToColor( features.title.subColor != null ? features.title.subColor : "#000000ff")); subtitle.setTextSize(TypedValue.COMPLEX_UNIT_PT, 6); subtitle.setVisibility(View.GONE); if (features.title.staticText != null) { title.setGravity(Gravity.CENTER); title.setText(features.title.staticText); } else { subtitle.setVisibility(View.VISIBLE); } } // WebView inAppWebView = new WebView(cordova.getActivity()); final ViewGroup.LayoutParams inAppWebViewParams = features.fullscreen ? new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT) : new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 0); if (!features.fullscreen) { ((LinearLayout.LayoutParams) inAppWebViewParams).weight = 1; } inAppWebView.setLayoutParams(inAppWebViewParams); inAppWebView.setWebChromeClient(new InAppChromeClient(thatWebView)); WebViewClient client = new ThemeableBrowserClient(thatWebView, new PageLoadListener() { @Override public void onPageStarted(String url) { if (inAppWebView != null && title != null && features.title != null && features.title.staticText == null && features.title.showPageTitle && features.title.loadingText != null) { title.setText(features.title.loadingText); subtitle.setText(url); } } @Override public void onPageFinished(String url, boolean canGoBack, boolean canGoForward) { if (inAppWebView != null && title != null && features.title != null && features.title.staticText == null && features.title.showPageTitle) { title.setText(inAppWebView.getTitle()); subtitle.setText(inAppWebView.getUrl()); } if (back != null) { back.setEnabled(canGoBack || features.backButtonCanClose); } if (forward != null) { forward.setEnabled(canGoForward); } } }); inAppWebView.setWebViewClient(client); WebSettings settings = inAppWebView.getSettings(); settings.setJavaScriptEnabled(true); settings.setJavaScriptCanOpenWindowsAutomatically(true); settings.setBuiltInZoomControls(features.zoom); settings.setDisplayZoomControls(false); settings.setPluginState(android.webkit.WebSettings.PluginState.ON); //Toggle whether this is enabled or not! Bundle appSettings = cordova.getActivity().getIntent().getExtras(); boolean enableDatabase = appSettings == null || appSettings.getBoolean("ThemeableBrowserStorageEnabled", true); if (enableDatabase) { String databasePath = cordova.getActivity().getApplicationContext() .getDir("themeableBrowserDB", Context.MODE_PRIVATE).getPath(); settings.setDatabasePath(databasePath); settings.setDatabaseEnabled(true); } settings.setDomStorageEnabled(true); if (features.clearcache) { CookieManager.getInstance().removeAllCookie(); } else if (features.clearsessioncache) { CookieManager.getInstance().removeSessionCookie(); } inAppWebView.loadUrl(url); inAppWebView.getSettings().setLoadWithOverviewMode(true); inAppWebView.getSettings().setUseWideViewPort(true); inAppWebView.requestFocus(); inAppWebView.requestFocusFromTouch(); // Add buttons to either leftButtonsContainer or // rightButtonsContainer according to user's alignment // configuration. int leftContainerWidth = 0; int rightContainerWidth = 0; if (features.customButtons != null) { for (int i = 0; i < features.customButtons.length; i++) { final BrowserButton buttonProps = features.customButtons[i]; final int index = i; Button button = createButton(buttonProps, String.format("custom button at %d", i), new View.OnClickListener() { @Override public void onClick(View view) { if (inAppWebView != null) { emitButtonEvent(buttonProps, inAppWebView.getUrl(), index); } } }); if (ALIGN_RIGHT.equals(buttonProps.align)) { rightButtonContainer.addView(button); rightContainerWidth += button.getLayoutParams().width; } else { leftButtonContainer.addView(button, 0); leftContainerWidth += button.getLayoutParams().width; } } } // Back and forward buttons must be added with special ordering logic such // that back button is always on the left of forward button if both buttons // are on the same side. if (forward != null && features.forwardButton != null && !ALIGN_RIGHT.equals(features.forwardButton.align)) { leftButtonContainer.addView(forward, 0); leftContainerWidth += forward.getLayoutParams().width; } if (back != null && features.backButton != null && ALIGN_RIGHT.equals(features.backButton.align)) { rightButtonContainer.addView(back); rightContainerWidth += back.getLayoutParams().width; } if (back != null && features.backButton != null && !ALIGN_RIGHT.equals(features.backButton.align)) { leftButtonContainer.addView(back, 0); leftContainerWidth += back.getLayoutParams().width; } if (forward != null && features.forwardButton != null && ALIGN_RIGHT.equals(features.forwardButton.align)) { rightButtonContainer.addView(forward); rightContainerWidth += forward.getLayoutParams().width; } if (menu != null) { if (features.menu != null && ALIGN_RIGHT.equals(features.menu.align)) { rightButtonContainer.addView(menu); rightContainerWidth += menu.getLayoutParams().width; } else { leftButtonContainer.addView(menu, 0); leftContainerWidth += menu.getLayoutParams().width; } } if (close != null) { if (features.closeButton != null && ALIGN_RIGHT.equals(features.closeButton.align)) { rightButtonContainer.addView(close); rightContainerWidth += close.getLayoutParams().width; } else { leftButtonContainer.addView(close, 0); leftContainerWidth += close.getLayoutParams().width; } } // Add the views to our toolbar toolbar.addView(leftButtonContainer); // Don't show address bar. // toolbar.addView(edittext); toolbar.addView(rightButtonContainer); if (title != null) { int titleMargin = Math.max(leftContainerWidth, rightContainerWidth); FrameLayout.LayoutParams titleParams = (FrameLayout.LayoutParams) title.getLayoutParams(); titleParams.setMargins(titleMargin, 8, titleMargin, 0); toolbar.addView(title); } if (subtitle != null) { int subtitleMargin = Math.max(leftContainerWidth, rightContainerWidth); FrameLayout.LayoutParams subtitleParams = (FrameLayout.LayoutParams) subtitle.getLayoutParams(); subtitleParams.setMargins(subtitleMargin, 0, subtitleMargin, 8); toolbar.addView(subtitle); } if (features.fullscreen) { // If full screen mode, we have to add inAppWebView before adding toolbar. main.addView(inAppWebView); } // Don't add the toolbar if its been disabled if (features.location) { // Add our toolbar to our main view/layout main.addView(toolbar); } if (!features.fullscreen) { // If not full screen, we add inAppWebView after adding toolbar. main.addView(inAppWebView); } WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); lp.copyFrom(dialog.getWindow().getAttributes()); lp.width = WindowManager.LayoutParams.MATCH_PARENT; lp.height = WindowManager.LayoutParams.MATCH_PARENT; dialog.setContentView(main); dialog.show(); dialog.getWindow().setAttributes(lp); // the goal of openhidden is to load the url and not display it // Show() needs to be called to cause the URL to be loaded if (features.hidden) { dialog.hide(); } } }; this.cordova.getActivity().runOnUiThread(runnable); return ""; }
From source file:org.telegram.ui.ThemeActivity.java
@Override public View createView(Context context) { actionBar.setBackButtonImage(R.drawable.ic_ab_back); actionBar.setAllowOverlayTitle(false); if (AndroidUtilities.isTablet()) { actionBar.setOccupyStatusBar(false); }/*from w ww.jav a 2s. c o m*/ if (currentType == THEME_TYPE_BASIC) { actionBar.setTitle(LocaleController.getString("ChatSettings", R.string.ChatSettings)); ActionBarMenu menu = actionBar.createMenu(); ActionBarMenuItem item = menu.addItem(0, R.drawable.ic_ab_other); item.addSubItem(create_theme, LocaleController.getString("CreateNewThemeMenu", R.string.CreateNewThemeMenu)); } else { actionBar.setTitle(LocaleController.getString("AutoNightTheme", R.string.AutoNightTheme)); } actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { @Override public void onItemClick(int id) { if (id == -1) { finishFragment(); } else if (id == create_theme) { if (getParentActivity() == null) { return; } AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setTitle(LocaleController.getString("NewTheme", R.string.NewTheme)); builder.setMessage( LocaleController.getString("CreateNewThemeAlert", R.string.CreateNewThemeAlert)); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); builder.setPositiveButton(LocaleController.getString("CreateTheme", R.string.CreateTheme), (dialog, which) -> openThemeCreate()); showDialog(builder.create()); } } }); listAdapter = new ListAdapter(context); FrameLayout frameLayout = new FrameLayout(context); frameLayout.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundGray)); fragmentView = frameLayout; listView = new RecyclerListView(context); listView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)); listView.setVerticalScrollBarEnabled(false); listView.setAdapter(listAdapter); ((DefaultItemAnimator) listView.getItemAnimator()).setDelayAnimations(false); frameLayout.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); listView.setOnItemClickListener((view, position) -> { if (position == enableAnimationsRow) { SharedPreferences preferences = MessagesController.getGlobalMainSettings(); boolean animations = preferences.getBoolean("view_animations", true); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("view_animations", !animations); editor.commit(); if (view instanceof TextCheckCell) { ((TextCheckCell) view).setChecked(!animations); } } else if (position == backgroundRow) { presentFragment(new WallpapersListActivity(WallpapersListActivity.TYPE_ALL)); } else if (position == sendByEnterRow) { SharedPreferences preferences = MessagesController.getGlobalMainSettings(); boolean send = preferences.getBoolean("send_by_enter", false); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("send_by_enter", !send); editor.commit(); if (view instanceof TextCheckCell) { ((TextCheckCell) view).setChecked(!send); } } else if (position == raiseToSpeakRow) { SharedConfig.toogleRaiseToSpeak(); if (view instanceof TextCheckCell) { ((TextCheckCell) view).setChecked(SharedConfig.raiseToSpeak); } } else if (position == saveToGalleryRow) { SharedConfig.toggleSaveToGallery(); if (view instanceof TextCheckCell) { ((TextCheckCell) view).setChecked(SharedConfig.saveToGallery); } } else if (position == customTabsRow) { SharedConfig.toggleCustomTabs(); if (view instanceof TextCheckCell) { ((TextCheckCell) view).setChecked(SharedConfig.customTabs); } } else if (position == directShareRow) { SharedConfig.toggleDirectShare(); if (view instanceof TextCheckCell) { ((TextCheckCell) view).setChecked(SharedConfig.directShare); } } else if (position == contactsReimportRow) { //not implemented } else if (position == contactsSortRow) { if (getParentActivity() == null) { return; } AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setTitle(LocaleController.getString("SortBy", R.string.SortBy)); builder.setItems( new CharSequence[] { LocaleController.getString("Default", R.string.Default), LocaleController.getString("SortFirstName", R.string.SortFirstName), LocaleController.getString("SortLastName", R.string.SortLastName) }, (dialog, which) -> { SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putInt("sortContactsBy", which); editor.commit(); if (listAdapter != null) { listAdapter.notifyItemChanged(position); } }); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); showDialog(builder.create()); } else if (position == stickersRow) { presentFragment(new StickersActivity(DataQuery.TYPE_IMAGE)); } else if (position == emojiRow) { if (getParentActivity() == null) { return; } final boolean maskValues[] = new boolean[2]; BottomSheet.Builder builder = new BottomSheet.Builder(getParentActivity()); builder.setApplyTopPadding(false); builder.setApplyBottomPadding(false); LinearLayout linearLayout = new LinearLayout(getParentActivity()); linearLayout.setOrientation(LinearLayout.VERTICAL); for (int a = 0; a < (Build.VERSION.SDK_INT >= 19 ? 2 : 1); a++) { String name = null; if (a == 0) { maskValues[a] = SharedConfig.allowBigEmoji; name = LocaleController.getString("EmojiBigSize", R.string.EmojiBigSize); } else if (a == 1) { maskValues[a] = SharedConfig.useSystemEmoji; name = LocaleController.getString("EmojiUseDefault", R.string.EmojiUseDefault); } CheckBoxCell checkBoxCell = new CheckBoxCell(getParentActivity(), 1, 21); checkBoxCell.setTag(a); checkBoxCell.setBackgroundDrawable(Theme.getSelectorDrawable(false)); linearLayout.addView(checkBoxCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 50)); checkBoxCell.setText(name, "", maskValues[a], true); checkBoxCell.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); checkBoxCell.setOnClickListener(v -> { CheckBoxCell cell = (CheckBoxCell) v; int num = (Integer) cell.getTag(); maskValues[num] = !maskValues[num]; cell.setChecked(maskValues[num], true); }); } BottomSheet.BottomSheetCell cell = new BottomSheet.BottomSheetCell(getParentActivity(), 1); cell.setBackgroundDrawable(Theme.getSelectorDrawable(false)); cell.setTextAndIcon(LocaleController.getString("Save", R.string.Save).toUpperCase(), 0); cell.setTextColor(Theme.getColor(Theme.key_dialogTextBlue2)); cell.setOnClickListener(v -> { try { if (visibleDialog != null) { visibleDialog.dismiss(); } } catch (Exception e) { FileLog.e(e); } SharedPreferences.Editor editor = MessagesController.getGlobalMainSettings().edit(); editor.putBoolean("allowBigEmoji", SharedConfig.allowBigEmoji = maskValues[0]); editor.putBoolean("useSystemEmoji", SharedConfig.useSystemEmoji = maskValues[1]); editor.commit(); if (listAdapter != null) { listAdapter.notifyItemChanged(position); } }); linearLayout.addView(cell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 50)); builder.setCustomView(linearLayout); showDialog(builder.create()); } else if (position >= themeStartRow && position < themeEndRow) { int p = position - themeStartRow; if (p >= 0 && p < Theme.themes.size()) { Theme.ThemeInfo themeInfo = Theme.themes.get(p); if (currentType == THEME_TYPE_BASIC) { if (themeInfo == Theme.getCurrentTheme()) { return; } NotificationCenter.getGlobalInstance() .postNotificationName(NotificationCenter.needSetDayNightTheme, themeInfo, false); } else { Theme.setCurrentNightTheme(themeInfo); } int count = listView.getChildCount(); for (int a = 0; a < count; a++) { View child = listView.getChildAt(a); if (child instanceof ThemeCell) { ((ThemeCell) child).updateCurrentThemeCheck(); } } } } else if (position == nightThemeRow) { presentFragment(new ThemeActivity(THEME_TYPE_NIGHT)); } else if (position == nightDisabledRow) { Theme.selectedAutoNightType = Theme.AUTO_NIGHT_TYPE_NONE; updateRows(); Theme.checkAutoNightThemeConditions(); } else if (position == nightScheduledRow) { Theme.selectedAutoNightType = Theme.AUTO_NIGHT_TYPE_SCHEDULED; if (Theme.autoNightScheduleByLocation) { updateSunTime(null, true); } updateRows(); Theme.checkAutoNightThemeConditions(); } else if (position == nightAutomaticRow) { Theme.selectedAutoNightType = Theme.AUTO_NIGHT_TYPE_AUTOMATIC; updateRows(); Theme.checkAutoNightThemeConditions(); } else if (position == scheduleLocationRow) { Theme.autoNightScheduleByLocation = !Theme.autoNightScheduleByLocation; TextCheckCell checkCell = (TextCheckCell) view; checkCell.setChecked(Theme.autoNightScheduleByLocation); updateRows(); if (Theme.autoNightScheduleByLocation) { updateSunTime(null, true); } Theme.checkAutoNightThemeConditions(); } else if (position == scheduleFromRow || position == scheduleToRow) { if (getParentActivity() == null) { return; } int currentHour; int currentMinute; if (position == scheduleFromRow) { currentHour = Theme.autoNightDayStartTime / 60; currentMinute = (Theme.autoNightDayStartTime - currentHour * 60); } else { currentHour = Theme.autoNightDayEndTime / 60; currentMinute = (Theme.autoNightDayEndTime - currentHour * 60); } final TextSettingsCell cell = (TextSettingsCell) view; TimePickerDialog dialog = new TimePickerDialog(getParentActivity(), (view1, hourOfDay, minute) -> { int time = hourOfDay * 60 + minute; if (position == scheduleFromRow) { Theme.autoNightDayStartTime = time; cell.setTextAndValue(LocaleController.getString("AutoNightFrom", R.string.AutoNightFrom), String.format("%02d:%02d", hourOfDay, minute), true); } else { Theme.autoNightDayEndTime = time; cell.setTextAndValue(LocaleController.getString("AutoNightTo", R.string.AutoNightTo), String.format("%02d:%02d", hourOfDay, minute), true); } }, currentHour, currentMinute, true); showDialog(dialog); } else if (position == scheduleUpdateLocationRow) { updateSunTime(null, true); } }); return fragmentView; }
From source file:com.mobicage.rogerthat.plugins.messaging.ServiceMessageDetailActivity.java
protected void updateMessageDetail(final boolean isUpdate) { T.UI();/*from ww w .j a v a 2 s . co m*/ // Set sender avatar ImageView avatarImage = (ImageView) findViewById(R.id.avatar); String sender = mCurrentMessage.sender; setAvatar(avatarImage, sender); // Set sender name TextView senderView = (TextView) findViewById(R.id.sender); final String senderName = mFriendsPlugin.getName(sender); senderView.setText(senderName == null ? sender : senderName); // Set timestamp TextView timestampView = (TextView) findViewById(R.id.timestamp); timestampView.setText(TimeUtils.getDayTimeStr(this, mCurrentMessage.timestamp * 1000)); // Set clickable region on top to go to friends detail final RelativeLayout messageHeader = (RelativeLayout) findViewById(R.id.message_header); messageHeader.setOnClickListener(getFriendDetailOnClickListener(mCurrentMessage.sender)); messageHeader.setVisibility(View.VISIBLE); // Set message TextView messageView = (TextView) findViewById(R.id.message); WebView web = (WebView) findViewById(R.id.webview); FrameLayout flay = (FrameLayout) findViewById(R.id.message_details); Resources resources = getResources(); flay.setBackgroundColor(resources.getColor(R.color.mc_background)); boolean showBranded = false; int darkSchemeTextColor = resources.getColor(android.R.color.primary_text_dark); int lightSchemeTextColor = resources.getColor(android.R.color.primary_text_light); senderView.setTextColor(lightSchemeTextColor); timestampView.setTextColor(lightSchemeTextColor); BrandingResult br = null; if (!TextUtils.isEmptyOrWhitespace(mCurrentMessage.branding)) { boolean brandingAvailable = false; try { brandingAvailable = mMessagingPlugin.getBrandingMgr().isBrandingAvailable(mCurrentMessage.branding); } catch (BrandingFailureException e1) { L.d(e1); } try { if (brandingAvailable) { br = mMessagingPlugin.getBrandingMgr().prepareBranding(mCurrentMessage); WebSettings settings = web.getSettings(); settings.setJavaScriptEnabled(false); settings.setBlockNetworkImage(false); web.loadUrl("file://" + br.file.getAbsolutePath()); web.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); if (br.color != null) { flay.setBackgroundColor(br.color); } if (!br.showHeader) { messageHeader.setVisibility(View.GONE); MarginLayoutParams mlp = (MarginLayoutParams) web.getLayoutParams(); mlp.setMargins(0, 0, 0, mlp.bottomMargin); } else if (br.scheme == ColorScheme.dark) { senderView.setTextColor(darkSchemeTextColor); timestampView.setTextColor(darkSchemeTextColor); } showBranded = true; } else { mMessagingPlugin.getBrandingMgr().queueGenericBranding(mCurrentMessage.branding); } } catch (BrandingFailureException e) { L.bug("Could not display message with branding: branding is available, but prepareBranding failed", e); } } if (showBranded) { web.setVisibility(View.VISIBLE); messageView.setVisibility(View.GONE); } else { web.setVisibility(View.GONE); messageView.setVisibility(View.VISIBLE); messageView.setText(mCurrentMessage.message); } // Add list of members who did not ack yet FlowLayout memberSummary = (FlowLayout) findViewById(R.id.member_summary); memberSummary.removeAllViews(); SortedSet<MemberStatusTO> memberSummarySet = new TreeSet<MemberStatusTO>(getMemberstatusComparator()); for (MemberStatusTO ms : mCurrentMessage.members) { if ((ms.status & MessagingPlugin.STATUS_ACKED) != MessagingPlugin.STATUS_ACKED && !ms.member.equals(mCurrentMessage.sender)) { memberSummarySet.add(ms); } } FlowLayout.LayoutParams flowLP = new FlowLayout.LayoutParams(2, 0); for (MemberStatusTO ms : memberSummarySet) { FrameLayout fl = new FrameLayout(this); fl.setLayoutParams(flowLP); memberSummary.addView(fl); fl.addView(createParticipantView(ms)); } memberSummary.setVisibility(memberSummarySet.size() < 2 ? View.GONE : View.VISIBLE); // Add members statuses final LinearLayout members = (LinearLayout) findViewById(R.id.members); members.removeAllViews(); final String myEmail = mService.getIdentityStore().getIdentity().getEmail(); boolean isMember = false; mSomebodyAnswered = false; for (MemberStatusTO ms : mCurrentMessage.members) { boolean showMember = true; View view = getLayoutInflater().inflate(R.layout.message_member_detail, null); // Set receiver avatar RelativeLayout rl = (RelativeLayout) view.findViewById(R.id.avatar); rl.addView(createParticipantView(ms)); // Set receiver name TextView receiverView = (TextView) view.findViewById(R.id.receiver); final String memberName = mFriendsPlugin.getName(ms.member); receiverView.setText(memberName == null ? sender : memberName); // Set received timestamp TextView receivedView = (TextView) view.findViewById(R.id.received_timestamp); if ((ms.status & MessagingPlugin.STATUS_RECEIVED) == MessagingPlugin.STATUS_RECEIVED) { final String humanTime = TimeUtils.getDayTimeStr(this, ms.received_timestamp * 1000); if (ms.member.equals(mCurrentMessage.sender)) receivedView.setText(getString(R.string.sent_at, humanTime)); else receivedView.setText(getString(R.string.received_at, humanTime)); } else { receivedView.setText(R.string.not_yet_received); } // Set replied timestamp TextView repliedView = (TextView) view.findViewById(R.id.acked_timestamp); if ((ms.status & MessagingPlugin.STATUS_ACKED) == MessagingPlugin.STATUS_ACKED) { mSomebodyAnswered = true; String acked_timestamp = TimeUtils.getDayTimeStr(this, ms.acked_timestamp * 1000); if (ms.button_id != null) { ButtonTO button = null; for (ButtonTO b : mCurrentMessage.buttons) { if (b.id.equals(ms.button_id)) { button = b; break; } } if (button == null) { repliedView.setText(getString(R.string.dismissed_at, acked_timestamp)); // Do not show sender as member if he hasn't clicked a // button showMember = !ms.member.equals(mCurrentMessage.sender); } else { repliedView.setText(getString(R.string.replied_at, button.caption, acked_timestamp)); } } else { if (ms.custom_reply == null) { // Do not show sender as member if he hasn't clicked a // button showMember = !ms.member.equals(mCurrentMessage.sender); repliedView.setText(getString(R.string.dismissed_at, acked_timestamp)); } else repliedView.setText(getString(R.string.replied_at, ms.custom_reply, acked_timestamp)); } } else { repliedView.setText(R.string.not_yet_replied); showMember = !ms.member.equals(mCurrentMessage.sender); } if (br != null && br.scheme == ColorScheme.dark) { receiverView.setTextColor(darkSchemeTextColor); receivedView.setTextColor(darkSchemeTextColor); repliedView.setTextColor(darkSchemeTextColor); } else { receiverView.setTextColor(lightSchemeTextColor); receivedView.setTextColor(lightSchemeTextColor); repliedView.setTextColor(lightSchemeTextColor); } if (showMember) members.addView(view); isMember |= ms.member.equals(myEmail); } boolean isLocked = (mCurrentMessage.flags & MessagingPlugin.FLAG_LOCKED) == MessagingPlugin.FLAG_LOCKED; boolean canEdit = isMember && !isLocked; // Add attachments LinearLayout attachmentLayout = (LinearLayout) findViewById(R.id.attachment_layout); attachmentLayout.removeAllViews(); if (mCurrentMessage.attachments.length > 0) { attachmentLayout.setVisibility(View.VISIBLE); for (final AttachmentTO attachment : mCurrentMessage.attachments) { View v = getLayoutInflater().inflate(R.layout.attachment_item, null); ImageView attachment_image = (ImageView) v.findViewById(R.id.attachment_image); if (AttachmentViewerActivity.CONTENT_TYPE_JPEG.equalsIgnoreCase(attachment.content_type) || AttachmentViewerActivity.CONTENT_TYPE_PNG.equalsIgnoreCase(attachment.content_type)) { attachment_image.setImageResource(R.drawable.attachment_img); } else if (AttachmentViewerActivity.CONTENT_TYPE_PDF.equalsIgnoreCase(attachment.content_type)) { attachment_image.setImageResource(R.drawable.attachment_pdf); } else if (AttachmentViewerActivity.CONTENT_TYPE_VIDEO_MP4 .equalsIgnoreCase(attachment.content_type)) { attachment_image.setImageResource(R.drawable.attachment_video); } else { attachment_image.setImageResource(R.drawable.attachment_unknown); L.d("attachment.content_type not known: " + attachment.content_type); } TextView attachment_text = (TextView) v.findViewById(R.id.attachment_text); attachment_text.setText(attachment.name); v.setOnClickListener(new SafeViewOnClickListener() { @Override public void safeOnClick(View v) { String downloadUrlHash = mMessagingPlugin .attachmentDownloadUrlHash(attachment.download_url); File attachmentsDir; try { attachmentsDir = mMessagingPlugin.attachmentsDir(mCurrentMessage.getThreadKey(), null); } catch (IOException e) { L.d("Unable to create attachment directory", e); UIUtils.showAlertDialog(ServiceMessageDetailActivity.this, "", R.string.unable_to_read_write_sd_card); return; } boolean attachmentAvailable = mMessagingPlugin.attachmentExists(attachmentsDir, downloadUrlHash); if (!attachmentAvailable) { try { attachmentsDir = mMessagingPlugin.attachmentsDir(mCurrentMessage.getThreadKey(), mCurrentMessage.key); } catch (IOException e) { L.d("Unable to create attachment directory", e); UIUtils.showAlertDialog(ServiceMessageDetailActivity.this, "", R.string.unable_to_read_write_sd_card); return; } attachmentAvailable = mMessagingPlugin.attachmentExists(attachmentsDir, downloadUrlHash); } if (!mService.getNetworkConnectivityManager().isConnected() && !attachmentAvailable) { AlertDialog.Builder builder = new AlertDialog.Builder( ServiceMessageDetailActivity.this); builder.setMessage(R.string.no_internet_connection_try_again); builder.setPositiveButton(R.string.rogerthat, null); AlertDialog dialog = builder.create(); dialog.show(); return; } if (IOUtils.shouldCheckExternalStorageAvailable()) { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { // Its all oke } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { if (!attachmentAvailable) { L.d("Unable to write to sd-card"); UIUtils.showAlertDialog(ServiceMessageDetailActivity.this, "", R.string.unable_to_read_write_sd_card); return; } } else { L.d("Unable to read or write to sd-card"); UIUtils.showAlertDialog(ServiceMessageDetailActivity.this, "", R.string.unable_to_read_write_sd_card); return; } } L.d("attachment.content_type: " + attachment.content_type); L.d("attachment.download_url: " + attachment.download_url); L.d("attachment.name: " + attachment.name); L.d("attachment.size: " + attachment.size); if (AttachmentViewerActivity.supportsContentType(attachment.content_type)) { Intent i = new Intent(ServiceMessageDetailActivity.this, AttachmentViewerActivity.class); i.putExtra("thread_key", mCurrentMessage.getThreadKey()); i.putExtra("message", mCurrentMessage.key); i.putExtra("content_type", attachment.content_type); i.putExtra("download_url", attachment.download_url); i.putExtra("name", attachment.name); i.putExtra("download_url_hash", downloadUrlHash); startActivity(i); } else { AlertDialog.Builder builder = new AlertDialog.Builder( ServiceMessageDetailActivity.this); builder.setMessage(getString(R.string.attachment_can_not_be_displayed_in_your_version, getString(R.string.app_name))); builder.setPositiveButton(R.string.rogerthat, null); AlertDialog dialog = builder.create(); dialog.show(); } } }); attachmentLayout.addView(v); } } else { attachmentLayout.setVisibility(View.GONE); } LinearLayout widgetLayout = (LinearLayout) findViewById(R.id.widget_layout); if (mCurrentMessage.form == null) { widgetLayout.setVisibility(View.GONE); } else { widgetLayout.setVisibility(View.VISIBLE); widgetLayout.setEnabled(canEdit); displayWidget(widgetLayout, br); } // Add buttons TableLayout tableLayout = (TableLayout) findViewById(R.id.buttons); tableLayout.removeAllViews(); for (final ButtonTO button : mCurrentMessage.buttons) { addButton(senderName, myEmail, mSomebodyAnswered, canEdit, tableLayout, button); } if (mCurrentMessage.form == null && (mCurrentMessage.flags & MessagingPlugin.FLAG_ALLOW_DISMISS) == MessagingPlugin.FLAG_ALLOW_DISMISS) { ButtonTO button = new ButtonTO(); button.caption = "Roger that!"; addButton(senderName, myEmail, mSomebodyAnswered, canEdit, tableLayout, button); } if (mCurrentMessage.broadcast_type != null) { L.d("Show broadcast spam control"); final RelativeLayout broadcastSpamControl = (RelativeLayout) findViewById(R.id.broadcast_spam_control); View broadcastSpamControlBorder = findViewById(R.id.broadcast_spam_control_border); final View broadcastSpamControlDivider = findViewById(R.id.broadcast_spam_control_divider); final LinearLayout broadcastSpamControlTextContainer = (LinearLayout) findViewById( R.id.broadcast_spam_control_text_container); TextView broadcastSpamControlText = (TextView) findViewById(R.id.broadcast_spam_control_text); final LinearLayout broadcastSpamControlSettingsContainer = (LinearLayout) findViewById( R.id.broadcast_spam_control_settings_container); TextView broadcastSpamControlSettingsText = (TextView) findViewById( R.id.broadcast_spam_control_settings_text); TextView broadcastSpamControlIcon = (TextView) findViewById(R.id.broadcast_spam_control_icon); broadcastSpamControlIcon.setTypeface(mFontAwesomeTypeFace); broadcastSpamControlIcon.setText(R.string.fa_bell); final FriendBroadcastInfo fbi = mFriendsPlugin.getFriendBroadcastFlowForMfr(mCurrentMessage.sender); if (fbi == null) { L.bug("BroadcastData was null for: " + mCurrentMessage.sender); collapseDetails(DETAIL_SECTIONS); return; } broadcastSpamControl.setVisibility(View.VISIBLE); broadcastSpamControlSettingsContainer.setOnClickListener(new SafeViewOnClickListener() { @Override public void safeOnClick(View v) { L.d("goto broadcast settings"); PressMenuIconRequestTO request = new PressMenuIconRequestTO(); request.coords = fbi.coords; request.static_flow_hash = fbi.staticFlowHash; request.hashed_tag = fbi.hashedTag; request.generation = fbi.generation; request.service = mCurrentMessage.sender; mContext = "MENU_" + UUID.randomUUID().toString(); request.context = mContext; request.timestamp = System.currentTimeMillis() / 1000; showTransmitting(null); Map<String, Object> userInput = new HashMap<String, Object>(); userInput.put("request", request.toJSONMap()); userInput.put("func", "com.mobicage.api.services.pressMenuItem"); MessageFlowRun mfr = new MessageFlowRun(); mfr.staticFlowHash = fbi.staticFlowHash; try { JsMfr.executeMfr(mfr, userInput, mService, true); } catch (EmptyStaticFlowException ex) { completeTransmit(null); AlertDialog.Builder builder = new AlertDialog.Builder(ServiceMessageDetailActivity.this); builder.setMessage(ex.getMessage()); builder.setPositiveButton(R.string.rogerthat, null); AlertDialog dialog = builder.create(); dialog.show(); return; } } }); UIUtils.showHint(this, mService, HINT_BROADCAST, R.string.hint_broadcast, mCurrentMessage.broadcast_type, mFriendsPlugin.getName(mCurrentMessage.sender)); broadcastSpamControlText .setText(getString(R.string.broadcast_subscribed_to, mCurrentMessage.broadcast_type)); broadcastSpamControlSettingsText.setText(fbi.label); int ligthAlpha = 180; int darkAlpha = 70; int alpha = ligthAlpha; if (br != null && br.scheme == ColorScheme.dark) { broadcastSpamControlIcon.setTextColor(getResources().getColor(android.R.color.black)); broadcastSpamControlBorder.setBackgroundColor(darkSchemeTextColor); broadcastSpamControlDivider.setBackgroundColor(darkSchemeTextColor); activity.setBackgroundColor(darkSchemeTextColor); broadcastSpamControlText.setTextColor(lightSchemeTextColor); broadcastSpamControlSettingsText.setTextColor(lightSchemeTextColor); int alpacolor = Color.argb(darkAlpha, Color.red(lightSchemeTextColor), Color.green(lightSchemeTextColor), Color.blue(lightSchemeTextColor)); broadcastSpamControl.setBackgroundColor(alpacolor); alpha = darkAlpha; } else { broadcastSpamControlIcon.setTextColor(getResources().getColor(android.R.color.white)); broadcastSpamControlBorder.setBackgroundColor(lightSchemeTextColor); broadcastSpamControlDivider.setBackgroundColor(lightSchemeTextColor); activity.setBackgroundColor(lightSchemeTextColor); broadcastSpamControlText.setTextColor(darkSchemeTextColor); broadcastSpamControlSettingsText.setTextColor(darkSchemeTextColor); int alpacolor = Color.argb(darkAlpha, Color.red(darkSchemeTextColor), Color.green(darkSchemeTextColor), Color.blue(darkSchemeTextColor)); broadcastSpamControl.setBackgroundColor(alpacolor); } if (br != null && br.color != null) { int alphaColor = Color.argb(alpha, Color.red(br.color), Color.green(br.color), Color.blue(br.color)); broadcastSpamControl.setBackgroundColor(alphaColor); } mService.postOnUIHandler(new SafeRunnable() { @Override protected void safeRun() throws Exception { int maxHeight = broadcastSpamControl.getHeight(); broadcastSpamControlDivider.getLayoutParams().height = maxHeight; broadcastSpamControlDivider.requestLayout(); broadcastSpamControlSettingsContainer.getLayoutParams().height = maxHeight; broadcastSpamControlSettingsContainer.requestLayout(); broadcastSpamControlTextContainer.getLayoutParams().height = maxHeight; broadcastSpamControlTextContainer.requestLayout(); int broadcastSpamControlWidth = broadcastSpamControl.getWidth(); android.view.ViewGroup.LayoutParams lp = broadcastSpamControlSettingsContainer .getLayoutParams(); lp.width = broadcastSpamControlWidth / 4; broadcastSpamControlSettingsContainer.setLayoutParams(lp); } }); } if (!isUpdate) collapseDetails(DETAIL_SECTIONS); }
From source file:plugin.google.maps.GoogleMaps.java
@SuppressWarnings("unused") private void showDialog(final JSONArray args, final CallbackContext callbackContext) { if (windowLayer != null) { return;//from w w w. ja v a 2 s .c o m } // window layout windowLayer = new LinearLayout(activity); windowLayer.setPadding(0, 0, 0, 0); LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); layoutParams.gravity = Gravity.TOP | Gravity.LEFT; windowLayer.setLayoutParams(layoutParams); // dialog window layer FrameLayout dialogLayer = new FrameLayout(activity); dialogLayer.setLayoutParams(layoutParams); //dialogLayer.setPadding(15, 15, 15, 0); dialogLayer.setBackgroundColor(Color.LTGRAY); windowLayer.addView(dialogLayer); // map frame final FrameLayout mapFrame = new FrameLayout(activity); mapFrame.setPadding(0, 0, 0, (int) (40 * density)); dialogLayer.addView(mapFrame); if (this.mPluginLayout != null && this.mPluginLayout.getMyView() != null) { this.mPluginLayout.detachMyView(); } ViewGroup.LayoutParams lParams = (ViewGroup.LayoutParams) mapView.getLayoutParams(); if (lParams == null) { lParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); } lParams.width = ViewGroup.LayoutParams.MATCH_PARENT; lParams.height = ViewGroup.LayoutParams.MATCH_PARENT; if (lParams instanceof AbsoluteLayout.LayoutParams) { AbsoluteLayout.LayoutParams params = (AbsoluteLayout.LayoutParams) lParams; params.x = 0; params.y = 0; mapView.setLayoutParams(params); } else if (lParams instanceof LinearLayout.LayoutParams) { LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) lParams; params.topMargin = 0; params.leftMargin = 0; mapView.setLayoutParams(params); } else if (lParams instanceof FrameLayout.LayoutParams) { FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) lParams; params.topMargin = 0; params.leftMargin = 0; mapView.setLayoutParams(params); } mapFrame.addView(this.mapView); // button frame LinearLayout buttonFrame = new LinearLayout(activity); buttonFrame.setOrientation(LinearLayout.HORIZONTAL); buttonFrame.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM); LinearLayout.LayoutParams buttonFrameParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT); buttonFrame.setLayoutParams(buttonFrameParams); dialogLayer.addView(buttonFrame); //close button LinearLayout.LayoutParams buttonParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1.0f); TextView closeLink = new TextView(activity); closeLink.setText("Close"); closeLink.setLayoutParams(buttonParams); closeLink.setTextColor(Color.BLUE); closeLink.setTextSize(20); closeLink.setGravity(Gravity.LEFT); closeLink.setPadding((int) (10 * density), 0, 0, (int) (10 * density)); closeLink.setOnClickListener(GoogleMaps.this); closeLink.setId(CLOSE_LINK_ID); buttonFrame.addView(closeLink); //license button TextView licenseLink = new TextView(activity); licenseLink.setText("Legal Notices"); licenseLink.setTextColor(Color.BLUE); licenseLink.setLayoutParams(buttonParams); licenseLink.setTextSize(20); licenseLink.setGravity(Gravity.RIGHT); licenseLink.setPadding((int) (10 * density), (int) (20 * density), (int) (10 * density), (int) (10 * density)); licenseLink.setOnClickListener(GoogleMaps.this); licenseLink.setId(LICENSE_LINK_ID); buttonFrame.addView(licenseLink); webView.setVisibility(View.GONE); root.addView(windowLayer); //Dummy view for the back-button event FrameLayout dummyLayout = new FrameLayout(activity); /* this.webView.showCustomView(dummyLayout, new WebChromeClient.CustomViewCallback() { @Override public void onCustomViewHidden() { mapFrame.removeView(mapView); if (mPluginLayout != null && mapDivLayoutJSON != null) { mPluginLayout.attachMyView(mapView); mPluginLayout.updateViewPosition(); } root.removeView(windowLayer); webView.setVisibility(View.VISIBLE); windowLayer = null; GoogleMaps.this.onMapEvent("map_close"); } }); */ this.sendNoResult(callbackContext); }
From source file:com.mods.grx.settings.GrxSettingsActivity.java
private void update_nav_header_bg() { boolean color_bg = true; if (getResources().getBoolean(R.bool.allow_user_panel_header_bg)) { String nav_header_file = Common.IconsDir + File.separator + getString(R.string.gs_nav_header_bg_image_name); File f = new File(nav_header_file); if (f.exists()) { update_text_panel_header_bg(getString(R.string.gs_image)); Bitmap bitmap = GrxImageHelper.load_bmp_image(nav_header_file); if (bitmap != null) { FrameLayout header = (FrameLayout) mSVN.getHeaderView() .findViewById(R.id.navigation_header_container); if (header != null) { header.setBackground(new BitmapDrawable(bitmap)); color_bg = false;// ww w . java 2 s .com } } } else update_text_panel_header_bg(getString(R.string.gs_default)); } if (color_bg) { FrameLayout header = (FrameLayout) mSVN.getHeaderView().findViewById(R.id.navigation_header_container); if (header != null) { TypedArray a = this.getTheme().obtainStyledAttributes(new int[] { R.attr.svn_nav_header_bg }); if (header != null) header.setBackgroundColor(a.getColor(0, 0)); a.recycle(); } } }
From source file:com.ckdroid.ilauncher.AllGridFragment.java
/** * Provide default implementation to return a simple grid view. Subclasses * can override to replace with their own layout. If doing so, the * returned view hierarchy <em>must</em> have a GridView whose id * is {@link android.R.id#list android.R.id.list} and can optionally * have a sibling view id {@link android.R.id#empty android.R.id.empty} * that is to be shown when the grid is empty. * <p/>//from w w w .jav a 2 s. c o m * <p>If you are overriding this method with your own custom content, * consider including the standard layout {@link android.R.layout#list_content} * in your layout file, so that you continue to retain all of the standard * behavior of ListFragment. In particular, this is currently the only * way to have the built-in indeterminant progress state be shown. */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final Context context = getActivity(); FrameLayout root = new FrameLayout(context); // ------------------------------------------------------------------ LinearLayout pframe = new LinearLayout(context); pframe.setId(INTERNAL_PROGRESS_CONTAINER_ID); pframe.setOrientation(LinearLayout.VERTICAL); pframe.setVisibility(View.GONE); pframe.setGravity(Gravity.CENTER); ProgressBar progress = new ProgressBar(context, null, android.R.attr.progressBarStyleLarge); pframe.addView(progress, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); root.addView(pframe, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); // ------------------------------------------------------------------ FrameLayout lframe = new FrameLayout(context); lframe.setId(INTERNAL_LIST_CONTAINER_ID); TextView tv = new TextView(getActivity()); tv.setId(INTERNAL_EMPTY_ID); tv.setGravity(Gravity.CENTER); lframe.addView(tv, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); GridView lv = new GridView(getActivity()); lv.setId(android.R.id.list); lv.setDrawSelectorOnTop(false); lv.setColumnWidth(convertDpToPixels(60, getActivity())); lv.setStretchMode(GridView.STRETCH_COLUMN_WIDTH); lv.setNumColumns(GridView.AUTO_FIT); lv.setHorizontalSpacing(convertDpToPixels(20, getActivity())); lv.setVerticalSpacing(convertDpToPixels(20, getActivity())); lv.setSmoothScrollbarEnabled(true); // disable overscroll if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { lv.setOverScrollMode(ListView.OVER_SCROLL_NEVER); } lframe.addView(lv, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); root.addView(lframe, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); // ------------------------------------------------------------------ root.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); root.setPadding(24, 30, 24, 30); root.setBackgroundColor(getResources().getColor(R.color.bg_white)); return root; }
From source file:org.telepatch.ui.ChatActivity.java
public View createView(LayoutInflater inflater, ViewGroup container) { if (fragmentView == null) { actionBarLayer.setDisplayHomeAsUpEnabled(true, R.drawable.ic_ab_back); if (AndroidUtilities.isTablet()) { actionBarLayer.setExtraLeftMargin(4); }/*from w w w . j av a2 s. c o m*/ actionBarLayer.setBackOverlay(R.layout.updating_state_layout); actionBarLayer.setActionBarMenuOnItemClick(new ActionBarLayer.ActionBarMenuOnItemClick() { @Override public void onItemClick(int id) { if (id == -1) { finishFragment(); } else if (id == -2) { selectedMessagesIds.clear(); selectedMessagesCanCopyIds.clear(); actionBarLayer.hideActionMode(); updateVisibleRows(); } else if (id == attach_photo) { try { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); File image = Utilities.generatePicturePath(); if (image != null) { takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(image)); currentPicturePath = image.getAbsolutePath(); } startActivityForResult(takePictureIntent, 0); } catch (Exception e) { FileLog.e("tmessages", e); } } else if (id == attach_gallery) { PhotoPickerActivity fragment = new PhotoPickerActivity(); fragment.setDelegate(new PhotoPickerActivity.PhotoPickerActivityDelegate() { @Override public void didSelectPhotos(ArrayList<String> photos) { SendMessagesHelper.prepareSendingPhotos(photos, null, dialog_id); } @Override public void startPhotoSelectActivity() { try { Intent photoPickerIntent = new Intent(Intent.ACTION_PICK); photoPickerIntent.setType("image/*"); startActivityForResult(photoPickerIntent, 1); } catch (Exception e) { FileLog.e("tmessages", e); } } }); presentFragment(fragment); } else if (id == attach_video) { try { Intent pickIntent = new Intent(); pickIntent.setType("video/*"); pickIntent.setAction(Intent.ACTION_GET_CONTENT); pickIntent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, (long) (1024 * 1024 * 1000)); Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE); File video = Utilities.generateVideoPath(); if (video != null) { if (Build.VERSION.SDK_INT >= 18) { takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(video)); } takeVideoIntent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, (long) (1024 * 1024 * 1000)); currentPicturePath = video.getAbsolutePath(); } Intent chooserIntent = Intent.createChooser(pickIntent, ""); chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { takeVideoIntent }); startActivityForResult(chooserIntent, 2); } catch (Exception e) { FileLog.e("tmessages", e); } } else if (id == attach_location) { if (!isGoogleMapsInstalled()) { return; } LocationActivity fragment = new LocationActivity(); fragment.setDelegate(new LocationActivity.LocationActivityDelegate() { @Override public void didSelectLocation(double latitude, double longitude) { SendMessagesHelper.getInstance().sendMessage(latitude, longitude, dialog_id); if (chatListView != null) { chatListView.setSelectionFromTop(messages.size() - 1, -100000 - chatListView.getPaddingTop()); } if (paused) { scrollToTopOnResume = true; } } }); presentFragment(fragment); } else if (id == attach_document) { DocumentSelectActivity fragment = new DocumentSelectActivity(); fragment.setDelegate(new DocumentSelectActivity.DocumentSelectActivityDelegate() { @Override public void didSelectFile(DocumentSelectActivity activity, String path) { activity.finishFragment(); SendMessagesHelper.prepareSendingDocument(path, path, dialog_id); } @Override public void startDocumentSelectActivity() { try { Intent photoPickerIntent = new Intent(Intent.ACTION_PICK); photoPickerIntent.setType("*/*"); startActivityForResult(photoPickerIntent, 21); } catch (Exception e) { FileLog.e("tmessages", e); } } }); presentFragment(fragment); } else if (id == chat_menu_avatar) { if (currentUser != null) { Bundle args = new Bundle(); args.putInt("user_id", currentUser.id); if (currentEncryptedChat != null) { args.putLong("dialog_id", dialog_id); } presentFragment(new UserProfileActivity(args)); } else if (currentChat != null) { if (info != null && info instanceof TLRPC.TL_chatParticipantsForbidden) { return; } int count = currentChat.participants_count; if (info != null) { count = info.participants.size(); } if (count == 0 || currentChat.left || currentChat instanceof TLRPC.TL_chatForbidden) { return; } Bundle args = new Bundle(); args.putInt("chat_id", currentChat.id); ChatProfileActivity fragment = new ChatProfileActivity(args); fragment.setChatInfo(info); presentFragment(fragment); } } else if (id == copy) { String str = ""; ArrayList<Integer> ids = new ArrayList<Integer>(selectedMessagesCanCopyIds.keySet()); if (currentEncryptedChat == null) { Collections.sort(ids); } else { Collections.sort(ids, Collections.reverseOrder()); } for (Integer messageId : ids) { MessageObject messageObject = selectedMessagesCanCopyIds.get(messageId); if (str.length() != 0) { str += "\n"; } if (messageObject.messageOwner.message != null) { str += messageObject.messageOwner.message; } else { str += messageObject.messageText; } } if (str.length() != 0) { if (Build.VERSION.SDK_INT < 11) { android.text.ClipboardManager clipboard = (android.text.ClipboardManager) ApplicationLoader.applicationContext .getSystemService(Context.CLIPBOARD_SERVICE); clipboard.setText(str); } else { android.content.ClipboardManager clipboard = (android.content.ClipboardManager) ApplicationLoader.applicationContext .getSystemService(Context.CLIPBOARD_SERVICE); android.content.ClipData clip = android.content.ClipData.newPlainText("label", str); clipboard.setPrimaryClip(clip); } } selectedMessagesIds.clear(); selectedMessagesCanCopyIds.clear(); actionBarLayer.hideActionMode(); updateVisibleRows(); } else if (id == delete) { ArrayList<Integer> ids = new ArrayList<Integer>(selectedMessagesIds.keySet()); ArrayList<Long> random_ids = null; if (currentEncryptedChat != null) { random_ids = new ArrayList<Long>(); for (HashMap.Entry<Integer, MessageObject> entry : selectedMessagesIds.entrySet()) { MessageObject msg = entry.getValue(); if (msg.messageOwner.random_id != 0 && msg.type != 10) { random_ids.add(msg.messageOwner.random_id); } } } //MessagesController.getInstance().deleteMessages(ids, random_ids, currentEncryptedChat); //TODO qui utilizzo un mio metodo per cancellare i messaggi, cosi' prima mostro un alert deleteMessages(ids, random_ids, currentEncryptedChat); actionBarLayer.hideActionMode(); } else if (id == forward) { Bundle args = new Bundle(); args.putBoolean("onlySelect", true); args.putBoolean("serverOnly", true); args.putString("selectAlertString", LocaleController.getString("ForwardMessagesTo", R.string.ForwardMessagesTo)); args.putString("selectAlertStringGroup", LocaleController .getString("ForwardMessagesToGroup", R.string.ForwardMessagesToGroup)); MessagesActivity fragment = new MessagesActivity(args); fragment.setDelegate(ChatActivity.this); presentFragment(fragment); } } }); updateSubtitle(); if (currentEncryptedChat != null) { actionBarLayer.setTitleIcon(R.drawable.ic_lock_white, AndroidUtilities.dp(4)); } else if (currentChat != null && currentChat.id < 0) { actionBarLayer.setTitleIcon(R.drawable.broadcast2, AndroidUtilities.dp(4)); } ActionBarMenu menu = actionBarLayer.createMenu(); if (currentEncryptedChat != null) { timeItem = menu.addItemResource(chat_enc_timer, R.layout.chat_header_enc_layout); } //TODO aggiungo il pulsante di ricerca item_search = menu.addItem(chat_menu_search, R.drawable.ic_ab_search); item_search.setIsSearchField(true) .setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() { @Override public void onSearchExpand() { searching = true; } @Override public void onSearchCollapse() { searching = false; //MessagesController.getInstance().loadMessages(dialog_id, 0, 20, maxMessageId, !cacheEndReaced, minDate, classGuid, false, false); //NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); } @Override public void onTextChanged(final EditText editText) { editText.requestFocus(); editText.setOnKeyListener(new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { boolean result = false; // se l'evento e' un "tasto premuto" sul tasto enter if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { //fai azione if (!editText.getText().toString().equals("")) { searchMessages(dialog_id, editText.getText().toString(), new FutureSearch()); try { presentFragment(new SearchResultsActivity( doSearchAndBlock(dialog_id, editText.getText().toString()), getArguments())); } catch (ExecutionException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } catch (NullPointerException e) { Log.e("xela92", "NullPointerException. Forse la connessione di rete e' assente? La ricerca stata annullata. "); e.printStackTrace(); } } result = true; } return result; } }); } }); ActionBarMenuItem item = menu.addItem(chat_menu_attach, R.drawable.ic_ab_attach); item.addSubItem(attach_photo, LocaleController.getString("ChatTakePhoto", R.string.ChatTakePhoto), R.drawable.ic_attach_photo); item.addSubItem(attach_gallery, LocaleController.getString("ChatGallery", R.string.ChatGallery), R.drawable.ic_attach_gallery); item.addSubItem(attach_video, LocaleController.getString("ChatVideo", R.string.ChatVideo), R.drawable.ic_attach_video); item.addSubItem(attach_document, LocaleController.getString("ChatDocument", R.string.ChatDocument), R.drawable.ic_ab_doc); item.addSubItem(attach_location, LocaleController.getString("ChatLocation", R.string.ChatLocation), R.drawable.ic_attach_location); menuItem = item; actionModeViews.clear(); final ActionBarMenu actionMode = actionBarLayer.createActionMode(); actionModeViews.add(actionMode.addItem(-2, R.drawable.ic_ab_done_gray, R.drawable.bar_selector_mode)); FrameLayout layout = new FrameLayout(actionMode.getContext()); layout.setBackgroundColor(0xffe5e5e5); actionMode.addView(layout); LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) layout.getLayoutParams(); layoutParams.width = AndroidUtilities.dp(1); layoutParams.height = LinearLayout.LayoutParams.MATCH_PARENT; layoutParams.topMargin = AndroidUtilities.dp(12); layoutParams.bottomMargin = AndroidUtilities.dp(12); layoutParams.gravity = Gravity.CENTER_VERTICAL; layout.setLayoutParams(layoutParams); actionModeViews.add(layout); selectedMessagesCountTextView = new TextView(actionMode.getContext()); selectedMessagesCountTextView.setTextSize(18); selectedMessagesCountTextView.setTextColor(0xff000000); selectedMessagesCountTextView.setSingleLine(true); selectedMessagesCountTextView.setLines(1); selectedMessagesCountTextView.setEllipsize(TextUtils.TruncateAt.END); selectedMessagesCountTextView.setPadding(AndroidUtilities.dp(11), 0, 0, 0); selectedMessagesCountTextView.setGravity(Gravity.CENTER_VERTICAL); selectedMessagesCountTextView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return true; } }); actionMode.addView(selectedMessagesCountTextView); layoutParams = (LinearLayout.LayoutParams) selectedMessagesCountTextView.getLayoutParams(); layoutParams.weight = 1; layoutParams.width = 0; layoutParams.height = LinearLayout.LayoutParams.MATCH_PARENT; selectedMessagesCountTextView.setLayoutParams(layoutParams); if (currentEncryptedChat == null) { actionModeViews .add(actionMode.addItem(copy, R.drawable.ic_ab_fwd_copy, R.drawable.bar_selector_mode)); actionModeViews.add( actionMode.addItem(forward, R.drawable.ic_ab_fwd_forward, R.drawable.bar_selector_mode)); actionModeViews .add(actionMode.addItem(delete, R.drawable.ic_ab_fwd_delete, R.drawable.bar_selector_mode)); } else { actionModeViews .add(actionMode.addItem(copy, R.drawable.ic_ab_fwd_copy, R.drawable.bar_selector_mode)); actionModeViews .add(actionMode.addItem(delete, R.drawable.ic_ab_fwd_delete, R.drawable.bar_selector_mode)); } actionMode.getItem(copy) .setVisibility(selectedMessagesCanCopyIds.size() != 0 ? View.VISIBLE : View.GONE); View avatarLayout = menu.addItemResource(chat_menu_avatar, R.layout.chat_header_layout); avatarImageView = (BackupImageView) avatarLayout.findViewById(R.id.chat_avatar_image); avatarImageView.processDetach = false; checkActionBarMenu(); fragmentView = inflater.inflate(R.layout.chat_layout, container, false); View contentView = fragmentView.findViewById(R.id.chat_layout); TextView emptyView = (TextView) fragmentView.findViewById(R.id.searchEmptyView); emptyViewContainer = fragmentView.findViewById(R.id.empty_view); emptyViewContainer.setVisibility(View.GONE); emptyViewContainer.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return true; } }); emptyView.setText(LocaleController.getString("NoMessages", R.string.NoMessages)); chatListView = (LayoutListView) fragmentView.findViewById(R.id.chat_list_view); chatListView.setAdapter(chatAdapter = new ChatAdapter(getParentActivity())); topPanel = fragmentView.findViewById(R.id.top_panel); topPlaneClose = (ImageView) fragmentView.findViewById(R.id.top_plane_close); topPanelText = (TextView) fragmentView.findViewById(R.id.top_panel_text); bottomOverlay = fragmentView.findViewById(R.id.bottom_overlay); bottomOverlayText = (TextView) fragmentView.findViewById(R.id.bottom_overlay_text); bottomOverlayChat = fragmentView.findViewById(R.id.bottom_overlay_chat); progressView = fragmentView.findViewById(R.id.progressLayout); pagedownButton = fragmentView.findViewById(R.id.pagedown_button); pagedownButton.setVisibility(View.GONE); View progressViewInner = progressView.findViewById(R.id.progressLayoutInner); updateContactStatus(); SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); int selectedBackground = preferences.getInt("selectedBackground", 1000001); int selectedColor = preferences.getInt("selectedColor", 0); if (selectedColor != 0) { contentView.setBackgroundColor(selectedColor); chatListView.setCacheColorHint(selectedColor); } else { chatListView.setCacheColorHint(0); try { if (selectedBackground == 1000001) { ((SizeNotifierRelativeLayout) contentView).setBackgroundImage(R.drawable.background_hd); } else { File toFile = new File(ApplicationLoader.applicationContext.getFilesDir(), "wallpaper.jpg"); if (toFile.exists()) { if (ApplicationLoader.cachedWallpaper != null) { ((SizeNotifierRelativeLayout) contentView) .setBackgroundImage(ApplicationLoader.cachedWallpaper); } else { Drawable drawable = Drawable.createFromPath(toFile.getAbsolutePath()); if (drawable != null) { ((SizeNotifierRelativeLayout) contentView).setBackgroundImage(drawable); ApplicationLoader.cachedWallpaper = drawable; } else { contentView.setBackgroundColor(-2693905); chatListView.setCacheColorHint(-2693905); } } isCustomTheme = true; } else { ((SizeNotifierRelativeLayout) contentView).setBackgroundImage(R.drawable.background_hd); } } } catch (Exception e) { contentView.setBackgroundColor(-2693905); chatListView.setCacheColorHint(-2693905); FileLog.e("tmessages", e); } } if (currentEncryptedChat != null) { emptyView.setVisibility(View.GONE); View secretChatPlaceholder = contentView.findViewById(R.id.secret_placeholder); secretChatPlaceholder.setVisibility(View.VISIBLE); if (isCustomTheme) { secretChatPlaceholder.setBackgroundResource(R.drawable.system_black); } else { secretChatPlaceholder.setBackgroundResource(R.drawable.system_blue); } secretViewStatusTextView = (TextView) contentView.findViewById(R.id.invite_text); secretChatPlaceholder.setPadding(AndroidUtilities.dp(16), AndroidUtilities.dp(12), AndroidUtilities.dp(16), AndroidUtilities.dp(12)); View v = contentView.findViewById(R.id.secret_placeholder); v.setVisibility(View.VISIBLE); if (currentEncryptedChat.admin_id == UserConfig.getClientUserId()) { if (currentUser.first_name.length() > 0) { secretViewStatusTextView .setText(LocaleController.formatString("EncryptedPlaceholderTitleOutgoing", R.string.EncryptedPlaceholderTitleOutgoing, currentUser.first_name)); } else { secretViewStatusTextView .setText(LocaleController.formatString("EncryptedPlaceholderTitleOutgoing", R.string.EncryptedPlaceholderTitleOutgoing, currentUser.last_name)); } } else { if (currentUser.first_name.length() > 0) { secretViewStatusTextView .setText(LocaleController.formatString("EncryptedPlaceholderTitleIncoming", R.string.EncryptedPlaceholderTitleIncoming, currentUser.first_name)); } else { secretViewStatusTextView .setText(LocaleController.formatString("EncryptedPlaceholderTitleIncoming", R.string.EncryptedPlaceholderTitleIncoming, currentUser.last_name)); } } updateSecretStatus(); } if (isCustomTheme) { progressViewInner.setBackgroundResource(R.drawable.system_loader2); emptyView.setBackgroundResource(R.drawable.system_black); } else { progressViewInner.setBackgroundResource(R.drawable.system_loader1); emptyView.setBackgroundResource(R.drawable.system_blue); } emptyView.setPadding(AndroidUtilities.dp(7), AndroidUtilities.dp(1), AndroidUtilities.dp(7), AndroidUtilities.dp(1)); if (currentUser != null && (currentUser.id / 1000 == 333 || currentUser.id % 1000 == 0)) { emptyView.setText(LocaleController.getString("GotAQuestion", R.string.GotAQuestion)); } chatListView.setOnItemLongClickListener(onItemLongClickListener); chatListView.setOnItemClickListener(onItemClickListener); final Rect scrollRect = new Rect(); chatListView.setOnInterceptTouchEventListener(new LayoutListView.OnInterceptTouchEventListener() { @Override public boolean onInterceptTouchEvent(MotionEvent event) { if (actionBarLayer.isActionModeShowed()) { return false; } if (event.getAction() == MotionEvent.ACTION_DOWN) { int x = (int) event.getX(); int y = (int) event.getY(); int count = chatListView.getChildCount(); Rect rect = new Rect(); for (int a = 0; a < count; a++) { View view = chatListView.getChildAt(a); int top = view.getTop(); int bottom = view.getBottom(); view.getLocalVisibleRect(rect); if (top > y || bottom < y) { continue; } if (!(view instanceof ChatMediaCell)) { break; } final ChatMediaCell cell = (ChatMediaCell) view; final MessageObject messageObject = cell.getMessageObject(); if (messageObject == null || !messageObject.isSecretPhoto() || !cell.getPhotoImage().isInsideImage(x, y - top)) { break; } File file = FileLoader.getPathToMessage(messageObject.messageOwner); if (!file.exists()) { break; } startX = x; startY = y; chatListView.setOnItemClickListener(null); openSecretPhotoRunnable = new Runnable() { @Override public void run() { if (openSecretPhotoRunnable == null) { return; } chatListView.requestDisallowInterceptTouchEvent(true); chatListView.setOnItemLongClickListener(null); chatListView.setLongClickable(false); openSecretPhotoRunnable = null; if (sendSecretMessageRead(messageObject)) { cell.invalidate(); } SecretPhotoViewer.getInstance().setParentActivity(getParentActivity()); SecretPhotoViewer.getInstance().openPhoto(messageObject); } }; AndroidUtilities.RunOnUIThread(openSecretPhotoRunnable, 100); return true; } } return false; } }); chatListView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (openSecretPhotoRunnable != null || SecretPhotoViewer.getInstance().isVisible()) { if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL || event.getAction() == MotionEvent.ACTION_POINTER_UP) { AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { chatListView.setOnItemClickListener(onItemClickListener); } }, 150); if (openSecretPhotoRunnable != null) { AndroidUtilities.CancelRunOnUIThread(openSecretPhotoRunnable); openSecretPhotoRunnable = null; try { Toast.makeText(v.getContext(), LocaleController.getString("PhotoTip", R.string.PhotoTip), Toast.LENGTH_SHORT).show(); } catch (Exception e) { FileLog.e("tmessages", e); } } else { if (SecretPhotoViewer.getInstance().isVisible()) { AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { chatListView.setOnItemLongClickListener(onItemLongClickListener); chatListView.setLongClickable(true); } }); SecretPhotoViewer.getInstance().closePhoto(); } } } else if (event.getAction() != MotionEvent.ACTION_DOWN) { if (SecretPhotoViewer.getInstance().isVisible()) { return true; } else if (openSecretPhotoRunnable != null) { if (event.getAction() == MotionEvent.ACTION_MOVE) { if (Math.hypot(startX - event.getX(), startY - event.getY()) > AndroidUtilities .dp(5)) { AndroidUtilities.CancelRunOnUIThread(openSecretPhotoRunnable); openSecretPhotoRunnable = null; } } else { AndroidUtilities.CancelRunOnUIThread(openSecretPhotoRunnable); openSecretPhotoRunnable = null; } } } } return false; } }); chatListView.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView absListView, int i) { } @Override public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (visibleItemCount > 0) { if (firstVisibleItem <= 10) { if (!endReached && !loading) { if (messagesByDays.size() != 0) { MessagesController.getInstance().loadMessages(dialog_id, 20, maxMessageId, !cacheEndReaced, minDate, classGuid, false, false, null); } else { MessagesController.getInstance().loadMessages(dialog_id, 20, 0, !cacheEndReaced, minDate, classGuid, false, false, null); } loading = true; } } if (firstVisibleItem + visibleItemCount >= totalItemCount - 6) { if (!unread_end_reached && !loadingForward) { MessagesController.getInstance().loadMessages(dialog_id, 20, minMessageId, true, maxDate, classGuid, false, true, null); loadingForward = true; } } if (firstVisibleItem + visibleItemCount == totalItemCount && unread_end_reached) { showPagedownButton(false, true); } } for (int a = 0; a < visibleItemCount; a++) { View view = absListView.getChildAt(a); if (view instanceof ChatMessageCell) { ChatMessageCell messageCell = (ChatMessageCell) view; messageCell.getLocalVisibleRect(scrollRect); messageCell.setVisiblePart(scrollRect.top, scrollRect.bottom - scrollRect.top); } } } }); bottomOverlayChatText = (TextView) fragmentView.findViewById(R.id.bottom_overlay_chat_text); TextView textView = (TextView) fragmentView.findViewById(R.id.secret_title); textView.setText( LocaleController.getString("EncryptedDescriptionTitle", R.string.EncryptedDescriptionTitle)); textView = (TextView) fragmentView.findViewById(R.id.secret_description1); textView.setText(LocaleController.getString("EncryptedDescription1", R.string.EncryptedDescription1)); textView = (TextView) fragmentView.findViewById(R.id.secret_description2); textView.setText(LocaleController.getString("EncryptedDescription2", R.string.EncryptedDescription2)); textView = (TextView) fragmentView.findViewById(R.id.secret_description3); textView.setText(LocaleController.getString("EncryptedDescription3", R.string.EncryptedDescription3)); textView = (TextView) fragmentView.findViewById(R.id.secret_description4); textView.setText(LocaleController.getString("EncryptedDescription4", R.string.EncryptedDescription4)); if (loading && messages.isEmpty()) { progressView.setVisibility(View.VISIBLE); chatListView.setEmptyView(null); } else { progressView.setVisibility(View.GONE); chatListView.setEmptyView(emptyViewContainer); } pagedownButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { scrollToLastMessage(); } }); bottomOverlayChat.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (getParentActivity() == null) { return; } AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); if (currentUser != null && userBlocked) { builder.setMessage(LocaleController.getString("AreYouSureUnblockContact", R.string.AreYouSureUnblockContact)); builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { MessagesController.getInstance().unblockUser(currentUser.id); } }); } else { builder.setMessage(LocaleController.getString("AreYouSureDeleteThisChat", R.string.AreYouSureDeleteThisChat)); builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { MessagesController.getInstance().deleteDialog(dialog_id, 0, false); finishFragment(); } }); } builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); showAlertDialog(builder); } }); updateBottomOverlay(); chatActivityEnterView.setContainerView(getParentActivity(), fragmentView); } else { ViewGroup parent = (ViewGroup) fragmentView.getParent(); if (parent != null) { parent.removeView(fragmentView); } } return fragmentView; }
From source file:com.nttec.everychan.ui.presentation.BoardFragment.java
@SuppressLint("InlinedApi") private void openGridGallery() { final int tnSize = resources.getDimensionPixelSize(R.dimen.post_thumbnail_size); class GridGalleryAdapter extends ArrayAdapter<Triple<AttachmentModel, String, String>> implements View.OnClickListener, AbsListView.OnScrollListener { private final GridView view; private boolean selectingMode = false; private boolean[] isSelected = null; private volatile boolean isBusy = false; public GridGalleryAdapter(GridView view, List<Triple<AttachmentModel, String, String>> list) { super(activity, 0, list); this.view = view; this.isSelected = new boolean[list.size()]; }//from w ww . j a v a 2s. c om @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) { if (isBusy) setNonBusy(); isBusy = false; } else isBusy = true; } private void setNonBusy() { if (!downloadThumbnails()) return; for (int i = 0; i < view.getChildCount(); ++i) { View v = view.getChildAt(i); Object tnTag = v.findViewById(R.id.post_thumbnail_image).getTag(); if (tnTag == null || tnTag == Boolean.FALSE) fill(view.getPositionForView(v), v, false); } } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = new FrameLayout(activity); convertView.setLayoutParams(new AbsListView.LayoutParams(tnSize, tnSize)); ImageView tnImage = new ImageView(activity); tnImage.setLayoutParams(new FrameLayout.LayoutParams(tnSize, tnSize, Gravity.CENTER)); tnImage.setScaleType(ImageView.ScaleType.CENTER_INSIDE); tnImage.setId(R.id.post_thumbnail_image); ((FrameLayout) convertView).addView(tnImage); } convertView.setTag(getItem(position).getLeft()); safeRegisterForContextMenu(convertView); convertView.setOnClickListener(this); fill(position, convertView, isBusy); if (isSelected[position]) { /*ImageView overlay = new ImageView(activity); overlay.setImageResource(android.R.drawable.checkbox_on_background);*/ FrameLayout overlay = new FrameLayout(activity); overlay.setBackgroundColor(Color.argb(128, 0, 255, 0)); if (((FrameLayout) convertView).getChildCount() < 2) ((FrameLayout) convertView).addView(overlay); } else { if (((FrameLayout) convertView).getChildCount() > 1) ((FrameLayout) convertView).removeViewAt(1); } return convertView; } private void safeRegisterForContextMenu(View view) { try { view.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() { @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { if (presentationModel == null) { Fragment currentFragment = MainApplication .getInstance().tabsSwitcher.currentFragment; if (currentFragment instanceof BoardFragment) { currentFragment.onCreateContextMenu(menu, v, menuInfo); } } else { BoardFragment.this.onCreateContextMenu(menu, v, menuInfo); } } }); } catch (Exception e) { Logger.e(TAG, e); } } @Override public void onClick(View v) { if (selectingMode) { int position = view.getPositionForView(v); isSelected[position] = !isSelected[position]; notifyDataSetChanged(); } else { BoardFragment fragment = BoardFragment.this; if (presentationModel == null) { Fragment currentFragment = MainApplication.getInstance().tabsSwitcher.currentFragment; if (currentFragment instanceof BoardFragment) fragment = (BoardFragment) currentFragment; } fragment.openAttachment((AttachmentModel) v.getTag()); } } private void fill(int position, View view, boolean isBusy) { AttachmentModel attachment = getItem(position).getLeft(); String attachmentHash = getItem(position).getMiddle(); ImageView tnImage = (ImageView) view.findViewById(R.id.post_thumbnail_image); if (attachment.thumbnail == null || attachment.thumbnail.length() == 0) { tnImage.setTag(Boolean.TRUE); tnImage.setImageResource(Attachments.getDefaultThumbnailResId(attachment.type)); return; } tnImage.setTag(Boolean.FALSE); CancellableTask imagesDownloadTask = BoardFragment.this.imagesDownloadTask; ExecutorService imagesDownloadExecutor = BoardFragment.this.imagesDownloadExecutor; if (presentationModel == null) { Fragment currentFragment = MainApplication.getInstance().tabsSwitcher.currentFragment; if (currentFragment instanceof BoardFragment) { imagesDownloadTask = ((BoardFragment) currentFragment).imagesDownloadTask; imagesDownloadExecutor = ((BoardFragment) currentFragment).imagesDownloadExecutor; } } bitmapCache.asyncGet(attachmentHash, attachment.thumbnail, tnSize, chan, localFile, imagesDownloadTask, tnImage, imagesDownloadExecutor, Async.UI_HANDLER, downloadThumbnails() && !isBusy, downloadThumbnails() ? (isBusy ? 0 : R.drawable.thumbnail_error) : Attachments.getDefaultThumbnailResId(attachment.type)); } public void setSelectingMode(boolean selectingMode) { this.selectingMode = selectingMode; if (!selectingMode) { Arrays.fill(isSelected, false); notifyDataSetChanged(); } } public void selectAll() { if (selectingMode) { Arrays.fill(isSelected, true); notifyDataSetChanged(); } } public void downloadSelected(final Runnable onFinish) { final Dialog progressDialog = ProgressDialog.show(activity, resources.getString(R.string.grid_gallery_dlg_title), resources.getString(R.string.grid_gallery_dlg_message), true, false); Async.runAsync(new Runnable() { @Override public void run() { BoardFragment fragment = BoardFragment.this; if (fragment.presentationModel == null) { Fragment currentFragment = MainApplication.getInstance().tabsSwitcher.currentFragment; if (currentFragment instanceof BoardFragment) fragment = (BoardFragment) currentFragment; } boolean flag = false; for (int i = 0; i < isSelected.length; ++i) if (isSelected[i]) if (!fragment.downloadFile(getItem(i).getLeft(), true)) flag = true; final boolean toast = flag; activity.runOnUiThread(new Runnable() { @Override public void run() { if (toast) Toast.makeText(activity, R.string.notification_download_exists_or_in_queue, Toast.LENGTH_LONG).show(); progressDialog.dismiss(); onFinish.run(); } }); } }); } } try { List<Triple<AttachmentModel, String, String>> list = presentationModel.getAttachments(); if (list == null) { Toast.makeText(activity, R.string.notifacation_updating_now, Toast.LENGTH_LONG).show(); return; } GridView grid = new GridView(activity); final GridGalleryAdapter gridAdapter = new GridGalleryAdapter(grid, list); grid.setNumColumns(GridView.AUTO_FIT); grid.setColumnWidth(tnSize); int spacing = (int) (resources.getDisplayMetrics().density * 5 + 0.5f); grid.setVerticalSpacing(spacing); grid.setHorizontalSpacing(spacing); grid.setPadding(spacing, spacing, spacing, spacing); grid.setAdapter(gridAdapter); grid.setOnScrollListener(gridAdapter); grid.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f)); final Button btnToSelecting = new Button(activity); btnToSelecting.setText(R.string.grid_gallery_select); CompatibilityUtils.setTextAppearance(btnToSelecting, android.R.style.TextAppearance_Small); btnToSelecting.setSingleLine(); btnToSelecting.setVisibility(View.VISIBLE); btnToSelecting.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); final LinearLayout layoutSelectingButtons = new LinearLayout(activity); layoutSelectingButtons.setOrientation(LinearLayout.HORIZONTAL); layoutSelectingButtons.setWeightSum(10f); Button btnDownload = new Button(activity); btnDownload.setLayoutParams( new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 3.25f)); btnDownload.setText(R.string.grid_gallery_download); CompatibilityUtils.setTextAppearance(btnDownload, android.R.style.TextAppearance_Small); btnDownload.setSingleLine(); Button btnSelectAll = new Button(activity); btnSelectAll.setLayoutParams( new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 3.75f)); btnSelectAll.setText(android.R.string.selectAll); CompatibilityUtils.setTextAppearance(btnSelectAll, android.R.style.TextAppearance_Small); btnSelectAll.setSingleLine(); Button btnCancel = new Button(activity); btnCancel.setLayoutParams(new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 3f)); btnCancel.setText(android.R.string.cancel); CompatibilityUtils.setTextAppearance(btnCancel, android.R.style.TextAppearance_Small); btnCancel.setSingleLine(); layoutSelectingButtons.addView(btnDownload); layoutSelectingButtons.addView(btnSelectAll); layoutSelectingButtons.addView(btnCancel); layoutSelectingButtons.setVisibility(View.GONE); layoutSelectingButtons.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); btnToSelecting.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { btnToSelecting.setVisibility(View.GONE); layoutSelectingButtons.setVisibility(View.VISIBLE); gridAdapter.setSelectingMode(true); } }); btnCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { btnToSelecting.setVisibility(View.VISIBLE); layoutSelectingButtons.setVisibility(View.GONE); gridAdapter.setSelectingMode(false); } }); btnSelectAll.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { gridAdapter.selectAll(); } }); btnDownload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { gridAdapter.downloadSelected(new Runnable() { @Override public void run() { btnToSelecting.setVisibility(View.VISIBLE); layoutSelectingButtons.setVisibility(View.GONE); gridAdapter.setSelectingMode(false); } }); } }); LinearLayout dlgLayout = new LinearLayout(activity); dlgLayout.setOrientation(LinearLayout.VERTICAL); dlgLayout.addView(btnToSelecting); dlgLayout.addView(layoutSelectingButtons); dlgLayout.addView(grid); Dialog gridDialog = new Dialog(activity); gridDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); gridDialog.setContentView(dlgLayout); gridDialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); gridDialog.show(); } catch (OutOfMemoryError oom) { MainApplication.freeMemory(); Logger.e(TAG, oom); Toast.makeText(activity, R.string.error_out_of_memory, Toast.LENGTH_LONG).show(); } }
From source file:org.telegram.ui.ChannelEditActivity.java
@Override public View createView(Context context) { actionBar.setBackButtonImage(R.drawable.ic_ab_back); actionBar.setAllowOverlayTitle(true); actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { @Override//w ww . j a v a 2s.co m public void onItemClick(int id) { if (id == -1) { finishFragment(); } else if (id == done_button) { if (donePressed) { return; } if (nameTextView.length() == 0) { Vibrator v = (Vibrator) getParentActivity().getSystemService(Context.VIBRATOR_SERVICE); if (v != null) { v.vibrate(200); } AndroidUtilities.shakeView(nameTextView, 2, 0); return; } donePressed = true; if (avatarUpdater.uploadingAvatar != null) { createAfterUpload = true; progressDialog = new ProgressDialog(getParentActivity()); progressDialog.setMessage(LocaleController.getString("Loading", R.string.Loading)); progressDialog.setCanceledOnTouchOutside(false); progressDialog.setCancelable(false); progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, LocaleController.getString("Cancel", R.string.Cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { createAfterUpload = false; progressDialog = null; donePressed = false; try { dialog.dismiss(); } catch (Exception e) { FileLog.e("tmessages", e); } } }); progressDialog.show(); return; } if (!currentChat.title.equals(nameTextView.getText().toString())) { MessagesController.getInstance().changeChatTitle(chatId, nameTextView.getText().toString()); } if (info != null && !info.about.equals(descriptionTextView.getText().toString())) { MessagesController.getInstance().updateChannelAbout(chatId, descriptionTextView.getText().toString(), info); } if (signMessages != currentChat.signatures) { currentChat.signatures = true; MessagesController.getInstance().toogleChannelSignatures(chatId, signMessages); } if (uploadedAvatar != null) { MessagesController.getInstance().changeChatAvatar(chatId, uploadedAvatar); } else if (avatar == null && currentChat.photo instanceof TLRPC.TL_chatPhoto) { MessagesController.getInstance().changeChatAvatar(chatId, null); } finishFragment(); } } }); ActionBarMenu menu = actionBar.createMenu(); doneButton = menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56)); LinearLayout linearLayout; fragmentView = new ScrollView(context); fragmentView.setBackgroundColor(ContextCompat.getColor(context, R.color.settings_background)); ScrollView scrollView = (ScrollView) fragmentView; scrollView.setFillViewport(true); linearLayout = new LinearLayout(context); scrollView.addView(linearLayout, new ScrollView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); linearLayout.setOrientation(LinearLayout.VERTICAL); actionBar.setTitle(LocaleController.getString("ChannelEdit", R.string.ChannelEdit)); LinearLayout linearLayout2 = new LinearLayout(context); linearLayout2.setOrientation(LinearLayout.VERTICAL); linearLayout2.setElevation(AndroidUtilities.dp(2)); linearLayout2.setBackgroundColor(ContextCompat.getColor(context, R.color.card_background)); linearLayout.addView(linearLayout2, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); FrameLayout frameLayout = new FrameLayout(context); linearLayout2.addView(frameLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); avatarImage = new BackupImageView(context); avatarImage.setRoundRadius(AndroidUtilities.dp(32)); avatarDrawable.setInfo(5, null, null, false); avatarDrawable.setDrawPhoto(true); frameLayout.addView(avatarImage, LayoutHelper.createFrame(64, 64, Gravity.TOP | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT), LocaleController.isRTL ? 0 : 16, 12, LocaleController.isRTL ? 16 : 0, 12)); avatarImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (getParentActivity() == null) { return; } AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); CharSequence[] items; if (avatar != null) { items = new CharSequence[] { LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley), LocaleController.getString("DeletePhoto", R.string.DeletePhoto) }; } else { items = new CharSequence[] { LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley) }; } builder.setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { if (i == 0) { avatarUpdater.openCamera(); } else if (i == 1) { avatarUpdater.openGallery(); } else if (i == 2) { avatar = null; uploadedAvatar = null; avatarImage.setImage(avatar, "50_50", avatarDrawable); } } }); showDialog(builder.create()); } }); nameTextView = new EditText(context); if (currentChat.megagroup) { nameTextView.setHint(LocaleController.getString("GroupName", R.string.GroupName)); } else { nameTextView.setHint(LocaleController.getString("EnterChannelName", R.string.EnterChannelName)); } nameTextView.setMaxLines(4); nameTextView.setGravity(Gravity.CENTER_VERTICAL | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT)); nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); //nameTextView.setHintTextColor(0xff979797); nameTextView.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI); nameTextView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES); nameTextView.setPadding(0, 0, 0, AndroidUtilities.dp(8)); InputFilter[] inputFilters = new InputFilter[1]; inputFilters[0] = new InputFilter.LengthFilter(100); nameTextView.setFilters(inputFilters); AndroidUtilities.clearCursorDrawable(nameTextView); nameTextView.setTextColor(ContextCompat.getColor(context, R.color.primary_text)); frameLayout.addView(nameTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL, LocaleController.isRTL ? 16 : 96, 0, LocaleController.isRTL ? 96 : 16, 0)); nameTextView.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) { } @Override public void afterTextChanged(Editable s) { avatarDrawable.setInfo(5, nameTextView.length() > 0 ? nameTextView.getText().toString() : null, null, false); avatarImage.invalidate(); } }); View lineView = new View(context); lineView.setBackgroundColor(ContextCompat.getColor(context, R.color.card_divider)); linearLayout.addView(lineView, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 1)); linearLayout2 = new LinearLayout(context); linearLayout2.setOrientation(LinearLayout.VERTICAL); linearLayout2.setBackgroundColor(ContextCompat.getColor(context, R.color.card_background)); linearLayout2.setElevation(AndroidUtilities.dp(2)); linearLayout.addView(linearLayout2, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); descriptionTextView = new EditText(context); descriptionTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); //descriptionTextView.setHintTextColor(0xff979797); descriptionTextView.setTextColor(ContextCompat.getColor(context, R.color.primary_text)); descriptionTextView.setPadding(0, 0, 0, AndroidUtilities.dp(6)); descriptionTextView.setBackgroundDrawable(null); descriptionTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); descriptionTextView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES | InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT); descriptionTextView.setImeOptions(EditorInfo.IME_ACTION_DONE); inputFilters = new InputFilter[1]; inputFilters[0] = new InputFilter.LengthFilter(255); descriptionTextView.setFilters(inputFilters); descriptionTextView.setHint(LocaleController.getString("DescriptionOptionalPlaceholder", R.string.DescriptionOptionalPlaceholder)); AndroidUtilities.clearCursorDrawable(descriptionTextView); linearLayout2.addView(descriptionTextView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 17, 12, 17, 6)); descriptionTextView.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { if (i == EditorInfo.IME_ACTION_DONE && doneButton != null) { doneButton.performClick(); return true; } return false; } }); descriptionTextView.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) { } @Override public void afterTextChanged(Editable editable) { } }); ShadowSectionCell sectionCell = new ShadowSectionCell(context); sectionCell.setSize(20); linearLayout.addView(sectionCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); if (currentChat.megagroup || !currentChat.megagroup) { frameLayout = new FrameLayout(context); frameLayout.setElevation(AndroidUtilities.dp(2)); frameLayout.setBackgroundColor(ContextCompat.getColor(context, R.color.card_background)); linearLayout.addView(frameLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); typeCell = new TextSettingsCell(context); updateTypeCell(); typeCell.setForeground(R.drawable.list_selector); frameLayout.addView(typeCell, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); lineView = new View(context); lineView.setBackgroundColor(ContextCompat.getColor(context, R.color.card_divider)); linearLayout.addView(lineView, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 1)); frameLayout = new FrameLayout(context); frameLayout.setElevation(AndroidUtilities.dp(2)); frameLayout.setBackgroundColor(ContextCompat.getColor(context, R.color.card_background)); linearLayout.addView(frameLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); if (!currentChat.megagroup) { TextCheckCell textCheckCell = new TextCheckCell(context); textCheckCell.setForeground(R.drawable.list_selector); textCheckCell.setTextAndCheck( LocaleController.getString("ChannelSignMessages", R.string.ChannelSignMessages), signMessages, false); frameLayout.addView(textCheckCell, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); textCheckCell.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { signMessages = !signMessages; ((TextCheckCell) v).setChecked(signMessages); } }); TextInfoPrivacyCell infoCell = new TextInfoPrivacyCell(context); //infoCell.setBackgroundResource(R.drawable.greydivider); infoCell.setText( LocaleController.getString("ChannelSignMessagesInfo", R.string.ChannelSignMessagesInfo)); linearLayout.addView(infoCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); } else { adminCell = new TextSettingsCell(context); updateAdminCell(); adminCell.setForeground(R.drawable.list_selector); frameLayout.addView(adminCell, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); adminCell.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Bundle args = new Bundle(); args.putInt("chat_id", chatId); args.putInt("type", 1); presentFragment(new ChannelUsersActivity(args)); } }); sectionCell = new ShadowSectionCell(context); sectionCell.setSize(20); linearLayout.addView(sectionCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); /*if (!currentChat.creator) { sectionCell.setBackgroundResource(R.drawable.greydivider_bottom); }*/ } } if (currentChat.creator) { frameLayout = new FrameLayout(context); frameLayout.setElevation(AndroidUtilities.dp(2)); frameLayout.setBackgroundColor(ContextCompat.getColor(context, R.color.card_background)); linearLayout.addView(frameLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); TextSettingsCell textCell = new TextSettingsCell(context); textCell.setTextColor(0xffed3d39); textCell.setBackgroundResource(R.drawable.list_selector); if (currentChat.megagroup) { textCell.setText(LocaleController.getString("DeleteMega", R.string.DeleteMega), false); } else { textCell.setText(LocaleController.getString("ChannelDelete", R.string.ChannelDelete), false); } frameLayout.addView(textCell, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); textCell.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); if (currentChat.megagroup) { builder.setMessage(LocaleController.getString("MegaDeleteAlert", R.string.MegaDeleteAlert)); } else { builder.setMessage( LocaleController.getString("ChannelDeleteAlert", R.string.ChannelDeleteAlert)); } builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { NotificationCenter.getInstance().removeObserver(this, NotificationCenter.closeChats); if (AndroidUtilities.isTablet()) { NotificationCenter.getInstance().postNotificationName( NotificationCenter.closeChats, -(long) chatId); } else { NotificationCenter.getInstance() .postNotificationName(NotificationCenter.closeChats); } MessagesController.getInstance().deleteUserFromChat(chatId, MessagesController.getInstance().getUser(UserConfig.getClientUserId()), info); finishFragment(); } }); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); showDialog(builder.create()); } }); TextInfoPrivacyCell infoCell = new TextInfoPrivacyCell(context); //infoCell.setBackgroundResource(R.drawable.greydivider_bottom); if (currentChat.megagroup) { infoCell.setText(LocaleController.getString("MegaDeleteInfo", R.string.MegaDeleteInfo)); } else { infoCell.setText(LocaleController.getString("ChannelDeleteInfo", R.string.ChannelDeleteInfo)); } linearLayout.addView(infoCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); } nameTextView.setText(currentChat.title); nameTextView.setSelection(nameTextView.length()); if (info != null) { descriptionTextView.setText(info.about); } if (currentChat.photo != null) { avatar = currentChat.photo.photo_small; avatarImage.setImage(avatar, "50_50", avatarDrawable); } else { avatarImage.setImageDrawable(avatarDrawable); } return fragmentView; }
From source file:ir.irani.telecam.ui.PasscodeActivity.java
@Override public View createView(Context context) { if (type != 3) { actionBar.setBackButtonImage(R.drawable.ic_ab_back); }// ww w . ja v a 2s .c om actionBar.setAllowOverlayTitle(false); actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { @Override public void onItemClick(int id) { if (id == -1) { finishFragment(); } else if (id == done_button) { if (passcodeSetStep == 0) { processNext(); } else if (passcodeSetStep == 1) { processDone(); } } else if (id == pin_item) { currentPasswordType = 0; updateDropDownTextView(); } else if (id == password_item) { currentPasswordType = 1; updateDropDownTextView(); } } }); fragmentView = new FrameLayout(context); FrameLayout frameLayout = (FrameLayout) fragmentView; if (type != 0) { ActionBarMenu menu = actionBar.createMenu(); menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56)); titleTextView = new TextView(context); titleTextView.setTextColor(0xff757575); if (type == 1) { if (UserConfig.passcodeHash.length() != 0) { titleTextView .setText(LocaleController.getString("EnterNewPasscode", R.string.EnterNewPasscode)); } else { titleTextView.setText( LocaleController.getString("EnterNewFirstPasscode", R.string.EnterNewFirstPasscode)); } } else { titleTextView .setText(LocaleController.getString("EnterCurrentPasscode", R.string.EnterCurrentPasscode)); } titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); titleTextView.setGravity(Gravity.CENTER_HORIZONTAL); frameLayout.addView(titleTextView); FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) titleTextView.getLayoutParams(); layoutParams.width = LayoutHelper.WRAP_CONTENT; layoutParams.height = LayoutHelper.WRAP_CONTENT; layoutParams.gravity = Gravity.CENTER_HORIZONTAL; layoutParams.topMargin = AndroidUtilities.dp(38); titleTextView.setLayoutParams(layoutParams); passwordEditText = new EditText(context); passwordEditText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20); passwordEditText.setTextColor(0xff000000); passwordEditText.setMaxLines(1); passwordEditText.setLines(1); passwordEditText.setGravity(Gravity.CENTER_HORIZONTAL); passwordEditText.setSingleLine(true); if (type == 1) { passcodeSetStep = 0; passwordEditText.setImeOptions(EditorInfo.IME_ACTION_NEXT); } else { passcodeSetStep = 1; passwordEditText.setImeOptions(EditorInfo.IME_ACTION_DONE); } passwordEditText.setTransformationMethod(PasswordTransformationMethod.getInstance()); passwordEditText.setTypeface(Typeface.DEFAULT); AndroidUtilities.clearCursorDrawable(passwordEditText); frameLayout.addView(passwordEditText); layoutParams = (FrameLayout.LayoutParams) passwordEditText.getLayoutParams(); layoutParams.topMargin = AndroidUtilities.dp(90); layoutParams.height = AndroidUtilities.dp(36); layoutParams.leftMargin = AndroidUtilities.dp(40); layoutParams.gravity = Gravity.TOP | Gravity.LEFT; layoutParams.rightMargin = AndroidUtilities.dp(40); layoutParams.width = LayoutHelper.MATCH_PARENT; passwordEditText.setLayoutParams(layoutParams); passwordEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { if (passcodeSetStep == 0) { processNext(); return true; } else if (passcodeSetStep == 1) { processDone(); return true; } return false; } }); passwordEditText.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) { } @Override public void afterTextChanged(Editable s) { if (passwordEditText.length() == 4) { if (type == 2 && UserConfig.passcodeType == 0) { processDone(); } else if (type == 1 && currentPasswordType == 0) { if (passcodeSetStep == 0) { processNext(); } else if (passcodeSetStep == 1) { processDone(); } } } } }); passwordEditText.setCustomSelectionActionModeCallback(new ActionMode.Callback() { public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return false; } public void onDestroyActionMode(ActionMode mode) { } public boolean onCreateActionMode(ActionMode mode, Menu menu) { return false; } public boolean onActionItemClicked(ActionMode mode, MenuItem item) { return false; } }); if (type == 1) { dropDownContainer = new ActionBarMenuItem(context, menu, 0); dropDownContainer.setSubMenuOpenSide(1); dropDownContainer.addSubItem(pin_item, LocaleController.getString("PasscodePIN", R.string.PasscodePIN), 0); dropDownContainer.addSubItem(password_item, LocaleController.getString("PasscodePassword", R.string.PasscodePassword), 0); actionBar.addView(dropDownContainer); layoutParams = (FrameLayout.LayoutParams) dropDownContainer.getLayoutParams(); layoutParams.height = LayoutHelper.MATCH_PARENT; layoutParams.width = LayoutHelper.WRAP_CONTENT; layoutParams.rightMargin = AndroidUtilities.dp(40); layoutParams.leftMargin = AndroidUtilities.isTablet() ? AndroidUtilities.dp(64) : AndroidUtilities.dp(56); layoutParams.gravity = Gravity.TOP | Gravity.LEFT; dropDownContainer.setLayoutParams(layoutParams); dropDownContainer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dropDownContainer.toggleSubMenu(); } }); dropDown = new TextView(context); dropDown.setGravity(Gravity.LEFT); dropDown.setSingleLine(true); dropDown.setLines(1); dropDown.setMaxLines(1); dropDown.setEllipsize(TextUtils.TruncateAt.END); dropDown.setTextColor(0xffffffff); dropDown.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); dropDown.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_arrow_drop_down, 0); dropDown.setCompoundDrawablePadding(AndroidUtilities.dp(4)); dropDown.setPadding(0, 0, AndroidUtilities.dp(10), 0); dropDownContainer.addView(dropDown); layoutParams = (FrameLayout.LayoutParams) dropDown.getLayoutParams(); layoutParams.width = LayoutHelper.WRAP_CONTENT; layoutParams.height = LayoutHelper.WRAP_CONTENT; layoutParams.leftMargin = AndroidUtilities.dp(16); layoutParams.gravity = Gravity.CENTER_VERTICAL; layoutParams.bottomMargin = AndroidUtilities.dp(1); dropDown.setLayoutParams(layoutParams); } else { actionBar.setTitle(LocaleController.getString("Passcode", R.string.Passcode)); } updateDropDownTextView(); } else { actionBar.setTitle(LocaleController.getString("Passcode", R.string.Passcode)); frameLayout.setBackgroundColor(0xfff0f0f0); listView = new ListView(context); listView.setDivider(null); listView.setDividerHeight(0); listView.setVerticalScrollBarEnabled(false); listView.setDrawSelectorOnTop(true); frameLayout.addView(listView); FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams(); layoutParams.width = LayoutHelper.MATCH_PARENT; layoutParams.height = LayoutHelper.MATCH_PARENT; layoutParams.gravity = Gravity.TOP; listView.setLayoutParams(layoutParams); listView.setAdapter(listAdapter = new ListAdapter(context)); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) { if (i == changePasscodeRow) { presentFragment(new PasscodeActivity(1)); } else if (i == passcodeRow) { TextCheckCell cell = (TextCheckCell) view; if (UserConfig.passcodeHash.length() != 0) { UserConfig.passcodeHash = ""; UserConfig.appLocked = false; UserConfig.saveConfig(false); int count = listView.getChildCount(); for (int a = 0; a < count; a++) { View child = listView.getChildAt(a); if (child instanceof TextSettingsCell) { TextSettingsCell textCell = (TextSettingsCell) child; textCell.setTextColor(0xffc6c6c6); break; } } cell.setChecked(UserConfig.passcodeHash.length() != 0); NotificationCenter.getInstance() .postNotificationName(NotificationCenter.didSetPasscode); } else { presentFragment(new PasscodeActivity(1)); } } else if (i == autoLockRow) { if (getParentActivity() == null) { return; } AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setTitle(LocaleController.getString("AutoLock", R.string.AutoLock)); final NumberPicker numberPicker = new NumberPicker(getParentActivity()); numberPicker.setMinValue(0); numberPicker.setMaxValue(4); if (UserConfig.autoLockIn == 0) { numberPicker.setValue(0); } else if (UserConfig.autoLockIn == 60) { numberPicker.setValue(1); } else if (UserConfig.autoLockIn == 60 * 5) { numberPicker.setValue(2); } else if (UserConfig.autoLockIn == 60 * 60) { numberPicker.setValue(3); } else if (UserConfig.autoLockIn == 60 * 60 * 5) { numberPicker.setValue(4); } numberPicker.setFormatter(new NumberPicker.Formatter() { @Override public String format(int value) { if (value == 0) { return LocaleController.getString("AutoLockDisabled", R.string.AutoLockDisabled); } else if (value == 1) { return LocaleController.formatString("AutoLockInTime", R.string.AutoLockInTime, LocaleController.formatPluralString("Minutes", 1)); } else if (value == 2) { return LocaleController.formatString("AutoLockInTime", R.string.AutoLockInTime, LocaleController.formatPluralString("Minutes", 5)); } else if (value == 3) { return LocaleController.formatString("AutoLockInTime", R.string.AutoLockInTime, LocaleController.formatPluralString("Hours", 1)); } else if (value == 4) { return LocaleController.formatString("AutoLockInTime", R.string.AutoLockInTime, LocaleController.formatPluralString("Hours", 5)); } return ""; } }); builder.setView(numberPicker); builder.setNegativeButton(LocaleController.getString("Done", R.string.Done), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { which = numberPicker.getValue(); if (which == 0) { UserConfig.autoLockIn = 0; } else if (which == 1) { UserConfig.autoLockIn = 60; } else if (which == 2) { UserConfig.autoLockIn = 60 * 5; } else if (which == 3) { UserConfig.autoLockIn = 60 * 60; } else if (which == 4) { UserConfig.autoLockIn = 60 * 60 * 5; } listView.invalidateViews(); UserConfig.saveConfig(false); } }); showDialog(builder.create()); } else if (i == fingerprintRow) { UserConfig.useFingerprint = !UserConfig.useFingerprint; UserConfig.saveConfig(false); ((TextCheckCell) view).setChecked(UserConfig.useFingerprint); } } }); } return fragmentView; }