List of usage examples for android.app Dialog findViewById
@Nullable public <T extends View> T findViewById(@IdRes int id)
From source file:com.nextgis.ngm_clink_monitoring.dialogs.YesNoDialog.java
@NonNull @Override//w ww. j a v a2 s.c o m public Dialog onCreateDialog(Bundle savedInstanceState) { // Idea from here // http://thanhcs.blogspot.ru/2014/10/android-custom-dialog-fragment.html Dialog dialog = new Dialog(getActivity()); Window window = dialog.getWindow(); window.requestFeature(Window.FEATURE_NO_TITLE); window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN); window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); dialog.setContentView(R.layout.dialog_yes_no); mIcon = (ImageView) dialog.findViewById(R.id.title_icon); mTitle = (TextView) dialog.findViewById(R.id.title_text); mDialogBodyScroll = (ScrollView) dialog.findViewById(R.id.dialog_body_scroll); mDialogBodyLayoutScrolled = (LinearLayout) dialog.findViewById(R.id.dialog_body_scrolled); mDialogBodyLayout = (LinearLayout) dialog.findViewById(R.id.dialog_body); mButtons = (TableLayout) dialog.findViewById(R.id.dialog_buttons_yn); mBtnPositive = (Button) dialog.findViewById(R.id.dialog_btn_positive_yn); mBtnNegative = (Button) dialog.findViewById(R.id.dialog_btn_negative_yn); if (null != mIconId) { mIcon.setVisibility(View.VISIBLE); mIcon.setImageResource(mIconId); } if (null != mTitleId) { mTitle.setText(mTitleId); } if (null != mTitleText) { mTitle.setText(mTitleText); } if (null != mMessageId) { setMessageView(); mMessage.setText(mMessageId); } if (null != mMessageText) { setMessageView(); mMessage.setText(mMessageText); } if (null != mView) { if (mAddScrollForView) { mDialogBodyScroll.setVisibility(View.VISIBLE); mDialogBodyLayoutScrolled.addView(mView); } else { mDialogBodyLayout.setVisibility(View.VISIBLE); mDialogBodyLayout.addView(mView); } } if (null != mPositiveTextId) { mButtons.setVisibility(View.VISIBLE); mBtnPositive.setVisibility(View.VISIBLE); mBtnPositive.setText(mPositiveTextId); } if (null != mPositiveText) { mButtons.setVisibility(View.VISIBLE); mBtnPositive.setVisibility(View.VISIBLE); mBtnPositive.setText(mPositiveText); } if (null != mNegativeTextId) { mButtons.setVisibility(View.VISIBLE); mBtnNegative.setVisibility(View.VISIBLE); mBtnNegative.setText(mNegativeTextId); } if (null != mNegativeText) { mButtons.setVisibility(View.VISIBLE); mBtnNegative.setVisibility(View.VISIBLE); mBtnNegative.setText(mNegativeText); } if (null != mOnPositiveClickedListener) { mButtons.setVisibility(View.VISIBLE); mBtnPositive.setVisibility(View.VISIBLE); mBtnPositive.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (null != mOnPositiveClickedListener) { mOnPositiveClickedListener.onPositiveClicked(); } dismiss(); } }); } if (null != mOnNegativeClickedListener) { mButtons.setVisibility(View.VISIBLE); mBtnNegative.setVisibility(View.VISIBLE); mBtnNegative.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (null != mOnNegativeClickedListener) { mOnNegativeClickedListener.onNegativeClicked(); } dismiss(); } }); } return dialog; }
From source file:in.shick.diode.threads.ThreadsListActivity.java
public static void fillThreadClickDialog(Dialog dialog, ThingInfo thingInfo, ThreadClickDialogOnClickListenerFactory threadClickDialogOnClickListenerFactory) { final TextView titleView = (TextView) dialog.findViewById(R.id.title); final TextView urlView = (TextView) dialog.findViewById(R.id.url); final TextView submissionStuffView = (TextView) dialog .findViewById(R.id.submissionTime_submitter_subreddit); final Button loginButton = (Button) dialog.findViewById(R.id.login_button); final Button linkButton = (Button) dialog.findViewById(R.id.thread_link_button); final Button commentsButton = (Button) dialog.findViewById(R.id.thread_comments_button); titleView.setText(thingInfo.getTitle()); urlView.setText(thingInfo.getUrl()); StringBuilder sb = new StringBuilder( Util.getTimeAgo(thingInfo.getCreated_utc(), dialog.getContext().getResources())).append(" by ") .append(thingInfo.getAuthor()).append(" to ").append(thingInfo.getSubreddit()); submissionStuffView.setText(sb);/*from w w w .j a v a 2 s.c o m*/ // Only show upvote/downvote if user is logged in if (RedditSettings.getInstance().isLoggedIn()) { loginButton.setVisibility(View.GONE); } else { loginButton.setVisibility(View.VISIBLE); loginButton.setOnClickListener(threadClickDialogOnClickListenerFactory.getLoginOnClickListener()); } Util.setStateOfUpvoteDownvoteButtons(dialog, RedditSettings.getInstance().isLoggedIn(), thingInfo, threadClickDialogOnClickListenerFactory.getVoteUpOnCheckedChangeListener(thingInfo), threadClickDialogOnClickListenerFactory.getVoteDownOnCheckedChangeListener(thingInfo)); // "link" button behaves differently for regular links vs. self posts and links to comments pages (e.g., bestof) if (thingInfo.isIs_self()) { // It's a self post. Both buttons do the same thing. linkButton.setEnabled(false); } else { linkButton.setOnClickListener(threadClickDialogOnClickListenerFactory.getLinkOnClickListener(thingInfo, RedditSettings.getInstance().isUseExternalBrowser())); linkButton.setEnabled(true); } // "comments" button is easy: always does the same thing commentsButton .setOnClickListener(threadClickDialogOnClickListenerFactory.getCommentsOnClickListener(thingInfo)); }
From source file:cs.umass.edu.prepare.view.activities.CalendarActivity.java
/** * Allows the user to set time for adherence data where the time is unknown. * @param medication the medication for which the adherence is being modified. * @param index the index of the adherence being modified, i.e. AM or PM. *///from w w w. j ava 2s . co m private void setTimeTaken(final Medication medication, final Calendar dateKey, final int index) { final Dialog dialog = new Dialog(this); dialog.setContentView(R.layout.dialog_set_time); final TimePicker timePicker = (TimePicker) dialog.findViewById(R.id.time_picker); Button cancelButton = (Button) dialog.findViewById(R.id.btn_time_cancel); cancelButton.setOnClickListener(v -> dialog.dismiss()); Button saveButton = (Button) dialog.findViewById(R.id.btn_time_save); saveButton.setOnClickListener(v -> { Calendar time = Utils.getTimeNoInterval(timePicker); // TODO: Store times taken Map<Medication, Adherence[]> dailyAdherence = adherenceData.get(dateKey); Adherence[] adherence = dailyAdherence.get(medication); adherence[index].setTimeTaken(time); Calendar[] schedule = dailySchedule.get(medication); Calendar timeToTake = (Calendar) time.clone(); timeToTake.set(Calendar.HOUR_OF_DAY, schedule[index].get(Calendar.HOUR_OF_DAY)); timeToTake.set(Calendar.MINUTE, schedule[index].get(Calendar.MINUTE)); Calendar upperBound = (Calendar) timeToTake.clone(); upperBound.add(Calendar.HOUR_OF_DAY, 1); Calendar lowerBound = (Calendar) timeToTake.clone(); lowerBound.add(Calendar.HOUR_OF_DAY, -1); if (time.after(upperBound) || time.before(lowerBound)) { adherence[index].setAdherenceType(Adherence.AdherenceType.TAKEN_EARLY_OR_LATE); } else { adherence[index].setAdherenceType(Adherence.AdherenceType.TAKEN); } dialog.dismiss(); refresh(); DataIO preferences = DataIO.getInstance(CalendarActivity.this); preferences.setAdherenceData(this, adherenceData); }); dialog.show(); }
From source file:de.dmxcontrol.activity.ControlActivity.java
private Dialog createSplashDialog() { Dialog dialog = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar); dialog.setContentView(R.layout.dialog_splash); ImageView image = (ImageView) dialog.findViewById(R.id.image_splash); image.setImageResource(R.drawable.image_splash); AnimationSet set = new AnimationSet(true); Animation animation = new AlphaAnimation(0.0f, 1.0f); animation.setDuration(500);//www . ja va2s . c om animation.setInterpolator( AnimationUtils.loadInterpolator(this, android.R.anim.accelerate_decelerate_interpolator)); set.addAnimation(animation); animation = new ScaleAnimation(0.0f, 1.0f, 0.0f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); animation.setDuration(1000); animation.setInterpolator( AnimationUtils.loadInterpolator(this, android.R.anim.accelerate_decelerate_interpolator)); set.addAnimation(animation); image.setAnimation(set); dismissSplashDelayed(); return dialog; }
From source file:com.kunze.androidlocaltodo.TaskListActivity.java
private void ShowTaskDialog(Task task, OnClickListener okListener) { LayoutInflater inflater = this.getLayoutInflater(); View dlgView = inflater.inflate(R.layout.dialog_task, null); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setView(dlgView);/* w w w. j ava 2 s. c o m*/ builder.setTitle("Task"); final TextView nameEdit = (TextView) dlgView.findViewById(R.id.task_name_edit); nameEdit.setText(task.mName); final TextView descriptionEdit = (TextView) dlgView.findViewById(R.id.task_description_edit); descriptionEdit.setText(task.mDescription); final TextView dueDateView = (TextView) dlgView.findViewById(R.id.task_due_date); SetFriendlyDueDateText(dueDateView, task.mDueDate); Button dueDateButton = (Button) dlgView.findViewById(R.id.task_due_date_choose); final Calendar dueDate = task.mDueDate; final Task thisTask = task; dueDateButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ShowDueDateDialog(dueDate, new OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int id) { Dialog dlg = (Dialog) dialogInterface; DatePicker datePicker = (DatePicker) dlg.findViewById(R.id.due_date_calendar); Calendar calendar = Calendar.getInstance(); calendar.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth()); thisTask.mDueDate = calendar; SetFriendlyDueDateText(dueDateView, thisTask.mDueDate); } }); } }); final CheckBox repeatCheck = (CheckBox) dlgView.findViewById(R.id.repeat); repeatCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { View dialog = (View) buttonView.getParent(); SetRepeatVisibility(dialog, isChecked); } }); Boolean repeat = task.mRepeatUnit != Task.RepeatUnit.NONE; repeatCheck.setChecked(repeat); SetRepeatVisibility(dlgView, repeat); final EditText repeatTimeEdit = (EditText) dlgView.findViewById(R.id.repeat_time); repeatTimeEdit.setText(Integer.toString(task.mRepeatTime)); final Spinner repeatUnitSpinner = (Spinner) dlgView.findViewById(R.id.repeat_unit); String[] repeatUnits = { "Days", "Weeks", "Months", "Years" }; repeatUnitSpinner .setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, repeatUnits)); int repeatUnitPos = 0; switch (task.mRepeatUnit) { case DAYS: repeatUnitPos = 0; break; case WEEKS: repeatUnitPos = 1; break; case MONTHS: repeatUnitPos = 2; break; case YEARS: repeatUnitPos = 3; break; case NONE: repeatUnitPos = 0; } repeatUnitSpinner.setSelection(repeatUnitPos); final RadioButton repeatFromComplete = (RadioButton) dlgView.findViewById(R.id.repeat_from_complete); final RadioButton repeatFromDue = (RadioButton) dlgView.findViewById(R.id.repeat_from_due); if (task.mRepeatFromComplete) { repeatFromComplete.setChecked(true); } else { repeatFromDue.setChecked(true); } // Here's a trick: We cascade the OnClick listeners so we can extract // the dialog contents into the task before calling the second listener. final OnClickListener userListener = okListener; final Task myTask = task; OnClickListener cascadedListener = new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { myTask.mName = nameEdit.getText().toString(); myTask.mDescription = descriptionEdit.getText().toString(); myTask.mRepeatUnit = Task.RepeatUnit.NONE; if (repeatCheck.isChecked()) { switch (repeatUnitSpinner.getSelectedItemPosition()) { case 0: myTask.mRepeatUnit = Task.RepeatUnit.DAYS; break; case 1: myTask.mRepeatUnit = Task.RepeatUnit.WEEKS; break; case 2: myTask.mRepeatUnit = Task.RepeatUnit.MONTHS; break; case 3: myTask.mRepeatUnit = Task.RepeatUnit.YEARS; break; } myTask.mRepeatTime = Integer.parseInt(repeatTimeEdit.getText().toString()); myTask.mRepeatFromComplete = repeatFromComplete.isChecked(); } userListener.onClick(dialog, which); } }; builder.setNegativeButton("Cancel", null); builder.setPositiveButton("OK", cascadedListener); builder.show(); }
From source file:com.zentri.otademo.OTAActivity.java
public void showSettingsMenu(final Settings settings) { //show dialog to enter firmware version string if (!mSettingsDialogOpen) { mSettingsDialogOpen = true;//www. j a va 2 s.c o m runOnUiThread(new Runnable() { @Override public void run() { AlertDialog.Builder builder = new AlertDialog.Builder(OTAActivity.this); LayoutInflater inflater = getLayoutInflater(); final View dialogView = inflater.inflate(R.layout.settings_dialog, (ViewGroup) findViewById(R.id.ota_view_root), false); // Inflate and set the layout for the dialog // Pass null as the parent view because its going in the dialog layout final EditText editText = (EditText) dialogView.findViewById(R.id.settings_editText); editText.setText(settings.getFirmwareFilename()); final CheckBox checkBox = (CheckBox) dialogView.findViewById(R.id.settings_use_latest_checkbox); if (settings.useLatest()) { editText.setEnabled(false); checkBox.setChecked(true); } else { editText.setEnabled(true); checkBox.setChecked(false); } checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { editText.setEnabled(false); } else { editText.setEnabled(true); } } }); builder.setView(dialogView) // Add action buttons .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { Dialog d = (Dialog) dialog; EditText editText = (EditText) d.findViewById(R.id.settings_editText); if (editText != null) { settings.setFirmwareFilename(editText.getText().toString()); settings.setUseLatest(checkBox.isChecked()); SettingsManager.saveSettings(OTAActivity.this, settings); //check for updates checkForUpdates(); mSettingsDialogOpen = false; } else { Log.d(TAG, "Couldn't get reference to settings editText!"); } } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mSettingsDialogOpen = false; dismissCurrentDialog(); } }).setCancelable(false).setTitle(R.string.settings_title); mCurrentDialog = builder.create(); mCurrentDialog.show(); Resources res = getResources(); Util.setTitleColour(res, mCurrentDialog, R.color.zentri_orange); Util.setDividerColour(res, mCurrentDialog, R.color.transparent); } }); } }
From source file:com.adithya321.sharesanalysis.fragments.SharePurchaseFragment.java
@Nullable @Override// ww w .j av a2s. c om public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_share_purchase, container, false); databaseHandler = new DatabaseHandler(getContext()); sharePurchasesRecyclerView = (RecyclerView) root.findViewById(R.id.share_purchases_recycler_view); emptyTV = (TextView) root.findViewById(R.id.empty); arrow = (ImageView) root.findViewById(R.id.arrow); setRecyclerViewAdapter(); FloatingActionButton addPurchaseFab = (FloatingActionButton) root.findViewById(R.id.add_purchase_fab); addPurchaseFab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final Dialog dialog = new Dialog(getContext()); dialog.setTitle("Add Share Purchase"); dialog.setContentView(R.layout.dialog_add_share_purchase); dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT); dialog.show(); final AutoCompleteTextView name = (AutoCompleteTextView) dialog.findViewById(R.id.share_name); List<String> nseList = ShareUtils.getNseList(getContext()); FilterWithSpaceAdapter<String> arrayAdapter = new FilterWithSpaceAdapter<>(getContext(), android.R.layout.simple_dropdown_item_1line, nseList); name.setThreshold(1); name.setAdapter(arrayAdapter); final Spinner spinner = (Spinner) dialog.findViewById(R.id.existing_spinner); ArrayList<String> shares = new ArrayList<>(); for (Share share : sharesList) { shares.add(share.getName()); } ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_item, shares); spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(spinnerAdapter); final RadioButton newRB = (RadioButton) dialog.findViewById(R.id.radioBtn_new); RadioButton existingRB = (RadioButton) dialog.findViewById(R.id.radioBtn_existing); if (shares.size() == 0) existingRB.setVisibility(View.GONE); (newRB).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { name.setVisibility(View.VISIBLE); spinner.setVisibility(View.GONE); } }); (existingRB).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { name.setVisibility(View.GONE); spinner.setVisibility(View.VISIBLE); } }); Calendar calendar = Calendar.getInstance(); year_start = calendar.get(Calendar.YEAR); month_start = calendar.get(Calendar.MONTH) + 1; day_start = calendar.get(Calendar.DAY_OF_MONTH); final Button selectDate = (Button) dialog.findViewById(R.id.select_date); selectDate.setText(new StringBuilder().append(day_start).append("/").append(month_start).append("/") .append(year_start)); selectDate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Dialog dialog = new DatePickerDialog(getActivity(), onDateSetListener, year_start, month_start - 1, day_start); dialog.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { selectDate.setText(new StringBuilder().append(day_start).append("/") .append(month_start).append("/").append(year_start)); } }); dialog.show(); } }); Button addPurchaseBtn = (Button) dialog.findViewById(R.id.add_purchase_btn); addPurchaseBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Share share = new Share(); share.setId(databaseHandler.getNextKey("share")); share.setPurchases(new RealmList<Purchase>()); Purchase purchase = new Purchase(); purchase.setId(databaseHandler.getNextKey("purchase")); if (newRB.isChecked()) { String sName = name.getText().toString().trim(); if (sName.equals("")) { Toast.makeText(getActivity(), "Invalid Name", Toast.LENGTH_SHORT).show(); return; } else { share.setName(sName); purchase.setName(sName); } } String stringStartDate = year_start + " " + month_start + " " + day_start; DateFormat format = new SimpleDateFormat("yyyy MM dd", Locale.ENGLISH); try { Date date = format.parse(stringStartDate); share.setDateOfInitialPurchase(date); purchase.setDate(date); } catch (Exception e) { Toast.makeText(getActivity(), "Invalid Date", Toast.LENGTH_SHORT).show(); return; } EditText quantity = (EditText) dialog.findViewById(R.id.no_of_shares); try { purchase.setQuantity(Integer.parseInt(quantity.getText().toString())); } catch (Exception e) { Toast.makeText(getActivity(), "Invalid Number of Shares", Toast.LENGTH_SHORT).show(); return; } EditText price = (EditText) dialog.findViewById(R.id.buying_price); try { purchase.setPrice(Double.parseDouble(price.getText().toString())); } catch (Exception e) { Toast.makeText(getActivity(), "Invalid Buying Price", Toast.LENGTH_SHORT).show(); return; } purchase.setType("buy"); if (newRB.isChecked()) { if (!databaseHandler.addShare(share, purchase)) { Toast.makeText(getActivity(), "Share Already Exists", Toast.LENGTH_SHORT).show(); return; } } else { purchase.setName(spinner.getSelectedItem().toString()); databaseHandler.addPurchase(spinner.getSelectedItem().toString(), purchase); } setRecyclerViewAdapter(); dialog.dismiss(); } }); } }); return root; }
From source file:net.sylvek.sharemyposition.ShareMyPosition.java
@Override protected void onPrepareDialog(int id, Dialog dialog) { switch (id) { default://from w ww. j a va 2s . c o m super.onPrepareDialog(id, dialog); break; case MAP_DLG: final View optionsLayout = (View) dialog.findViewById(R.id.custom_layout); final FrameLayout map = (FrameLayout) dialog.findViewById(R.id.sharedmap); /* to catch dismiss event from AlertControler, we need to "override" onClickListener */ final Button neutral = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_NEUTRAL); neutral.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { if (optionsLayout.getVisibility() == View.GONE) { optionsLayout.setVisibility(View.VISIBLE); map.setVisibility(View.GONE); neutral.setText(R.string.hide); } else { optionsLayout.setVisibility(View.GONE); map.setVisibility(View.VISIBLE); neutral.setText(R.string.options); } } }); if (location != null && sharedMap != null) { sharedMap.getController().setZoom(ZOOM_LEVEL); sharedMap.getController().setCenter(new GeoPoint(location.getLatitude(), location.getLongitude())); } if (!isConnected()) { final CheckBox geocodeAddress = (CheckBox) dialog.findViewById(R.id.add_address_location); geocodeAddress.setEnabled(false); neutral.setEnabled(false); map.setVisibility(View.GONE); optionsLayout.setVisibility(View.VISIBLE); } break; } }
From source file:com.amazonaws.cognito.sync.demo.MainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); Log.i(TAG, "onCreate"); /**// w w w . j a v a2 s. com * Initialize Facebook SDK */ FacebookSdk.sdkInitialize(getApplicationContext()); callbackManager = CallbackManager.Factory.create(); //Twitter if (mOauthConsumer == null) { mOauthProvider = new DefaultOAuthProvider("https://api.twitter.com/oauth/request_token", "https://api.twitter.com/oauth/access_token", "https://api.twitter.com/oauth/authorize"); mOauthConsumer = new DefaultOAuthConsumer(getString(R.string.twitter_consumer_key), getString(R.string.twitter_consumer_secret)); } retrieveTwitterCredentials(getIntent()); //If access token is already here, set fb session final AccessToken fbAccessToken = AccessToken.getCurrentAccessToken(); if (fbAccessToken != null) { setFacebookSession(fbAccessToken); btnLoginFacebook.setVisibility(View.GONE); } /** * Initializes the sync client. This must be call before you can use it. */ CognitoSyncClientManager.init(this); btnLoginFacebook = (Button) findViewById(R.id.btnLoginFacebook); btnLoginFacebook.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // start Facebook Login LoginManager.getInstance().logInWithReadPermissions(MainActivity.this, Arrays.asList("public_profile")); LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { btnLoginFacebook.setVisibility(View.GONE); new GetFbName(loginResult).execute(); setFacebookSession(loginResult.getAccessToken()); } @Override public void onCancel() { Toast.makeText(MainActivity.this, "Facebook login cancelled", Toast.LENGTH_LONG).show(); } @Override public void onError(FacebookException error) { Toast.makeText(MainActivity.this, "Error in Facebook login " + error.getMessage(), Toast.LENGTH_LONG).show(); } }); } }); btnLoginFacebook.setEnabled(getString(R.string.facebook_app_id) != "facebook_app_id"); try { mAuthManager = new AmazonAuthorizationManager(this, Bundle.EMPTY); } catch (IllegalArgumentException e) { Log.d(TAG, "Login with Amazon isn't configured correctly. " + "Thus it's disabled in this demo."); } btnLoginLWA = (Button) findViewById(R.id.btnLoginLWA); btnLoginLWA.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mAuthManager.authorize(APP_SCOPES, Bundle.EMPTY, new AuthorizeListener()); } }); btnLoginLWA.setEnabled(mAuthManager != null); Button btnWipedata = (Button) findViewById(R.id.btnWipedata); btnWipedata.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { new AlertDialog.Builder(MainActivity.this).setTitle("Wipe data?") .setMessage("This will log off your current session and wipe all user data. " + "Any data not synchronized will be lost.") .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // clear login status if (fbAccessToken != null) { LoginManager.getInstance().logOut(); } btnLoginFacebook.setVisibility(View.VISIBLE); if (mAuthManager != null) { mAuthManager.clearAuthorizationState(null); } btnLoginLWA.setVisibility(View.VISIBLE); // wipe data CognitoSyncClientManager.getInstance().wipeData(); // Wipe shared preferences AmazonSharedPreferencesWrapper .wipe(PreferenceManager.getDefaultSharedPreferences(MainActivity.this)); } }).setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }).show(); } }); findViewById(R.id.btnListDatasets).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, ListDatasetsActivity.class); startActivity(intent); } }); btnLoginDevAuth = (Button) findViewById(R.id.btnLoginDevAuth); if ((CognitoSyncClientManager.credentialsProvider .getIdentityProvider()) instanceof DeveloperAuthenticationProvider) { btnLoginDevAuth.setEnabled(true); Log.w(TAG, "Developer authentication feature configured correctly. "); } else { btnLoginDevAuth.setEnabled(false); Log.w(TAG, "Developer authentication feature configured incorrectly. " + "Thus it's disabled in this demo."); } btnLoginDevAuth.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // username and password dialog final Dialog login = new Dialog(MainActivity.this); login.setContentView(R.layout.login_dialog); login.setTitle("Sample developer login"); final TextView txtUsername = (TextView) login.findViewById(R.id.txtUsername); txtUsername.setHint("Username"); final TextView txtPassword = (TextView) login.findViewById(R.id.txtPassword); txtPassword.setHint("Password"); Button btnLogin = (Button) login.findViewById(R.id.btnLogin); Button btnCancel = (Button) login.findViewById(R.id.btnCancel); btnCancel.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { login.dismiss(); } }); btnLogin.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Validate the username and password if (txtUsername.getText().toString().isEmpty() || txtPassword.getText().toString().isEmpty()) { new AlertDialog.Builder(MainActivity.this).setTitle("Login error") .setMessage("Username or password cannot be empty!!").show(); } else { // Clear the existing credentials CognitoSyncClientManager.credentialsProvider.clearCredentials(); // Initiate user authentication against the // developer backend in this case the sample Cognito // developer authentication application. ((DeveloperAuthenticationProvider) CognitoSyncClientManager.credentialsProvider .getIdentityProvider()).login(txtUsername.getText().toString(), txtPassword.getText().toString(), MainActivity.this); } login.dismiss(); } }); login.show(); } }); /** * Button that leaves the app and launches the Twitter site to get an authorization. * If the user grants permissions to our app, it will be redirected to us again through * a callback. */ Button btnLoginTwitter = (Button) findViewById(R.id.btnLoginTwitter); btnLoginTwitter.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread(new Runnable() { @Override public void run() { try { String callbackUrl = "callback://" + getString(R.string.twitter_callback_url); String authUrl = mOauthProvider.retrieveRequestToken(mOauthConsumer, callbackUrl); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)); startActivity(intent); } catch (Exception e) { Log.w("oauth fail", e); } } }).start(); } }); btnLoginTwitter.setEnabled(getString(R.string.twitter_consumer_secret) != "twitter_consumer_secret"); }
From source file:com.amazon.appstream.fireclient.ConnectDialogFragment.java
/** * Create callback; performs initial set-up. *///from w ww . ja va 2s . c om @Override public Dialog onCreateDialog(Bundle savedInstanceState) { mEmpty.setAlpha(0); final Dialog connectDialog = new Dialog(getActivity()); connectDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); connectDialog.setCanceledOnTouchOutside(false); connectDialog.setCancelable(false); connectDialog.setContentView(R.layout.server_address); connectDialog.getWindow().setBackgroundDrawable(mEmpty); mAddressTitle = (TextView) connectDialog.findViewById(R.id.address_title); mAddressField = (TextView) connectDialog.findViewById(R.id.address); mTextEntryFields = connectDialog.findViewById(R.id.text_entry_fields); mProgressBar = (ProgressBar) connectDialog.findViewById(R.id.progress_bar); mUseHardware = (CheckBox) connectDialog.findViewById(R.id.hardware); mUseHardware.setChecked(false); final CheckBox useAppServerBox = (CheckBox) connectDialog.findViewById(R.id.appserver); useAppServerBox.setChecked(mUseAppServer); useAppServerBox.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { if (!mUseAppServer) { mDESServerAddress = mAddressField.getText().toString(); } } else { if (mUseAppServer) { mServerAddress = mAddressField.getText().toString(); } } mUseAppServer = isChecked; updateFields(); } }); mAppIdField = (TextView) connectDialog.findViewById(R.id.appid); mSpace1 = connectDialog.findViewById(R.id.space1); mSpace2 = connectDialog.findViewById(R.id.space2); mAppIdTitle = connectDialog.findViewById(R.id.appid_title); mUserIdTitle = connectDialog.findViewById(R.id.userid_title); if (mAppId != null) { mAppIdField.setText(mAppId); } mUserIdField = (TextView) connectDialog.findViewById(R.id.userid); if (mUsername != null) { mUserIdField.setText(mUsername); } mErrorMessageField = (TextView) connectDialog.findViewById(R.id.error_message); mReconnect = connectDialog.findViewById(R.id.reconnect_fields); mReconnectMessage = (TextView) connectDialog.findViewById(R.id.reconnect_message); final Button connectButton = (Button) connectDialog.findViewById(R.id.connect); connectButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { onConnect(); } }); TextView.OnEditorActionListener listener = new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_GO) { InputMethodManager imm = (InputMethodManager) mActivity .getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(mUserIdField.getWindowToken(), 0); onConnect(); } return true; } }; View.OnFocusChangeListener focusListener = new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { connectButton.setFocusableInTouchMode(false); } }; mAppIdField.setOnFocusChangeListener(focusListener); mUserIdField.setOnFocusChangeListener(focusListener); mUserIdField.setOnFocusChangeListener(focusListener); mUserIdField.setOnEditorActionListener(listener); updateFields(); if (mAddressField.getText().length() == 0) { mAddressField.requestFocus(); connectButton.setFocusableInTouchMode(false); } else { connectButton.requestFocus(); } if (mReconnectMessageString != null) { reconnecting(mReconnectMessageString); mReconnectMessageString = null; } return connectDialog; }