androidx.appcompat.app.AppCompatActivity Java Examples

The following examples show how to use androidx.appcompat.app.AppCompatActivity. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: VenmoUnitTest.java    From braintree_android with MIT License 6 votes vote down vote up
@Test
public void onActivityResult_postsPaymentMethodNonceOnSuccess() {
    BraintreeFragment fragment = new MockFragmentBuilder()
            .build();
    Intent intent = new Intent()
            .putExtra(Venmo.EXTRA_PAYMENT_METHOD_NONCE, "123456-12345-12345-a-adfa")
            .putExtra(Venmo.EXTRA_USERNAME, "username");

    Venmo.onActivityResult(fragment, AppCompatActivity.RESULT_OK, intent);

    ArgumentCaptor<VenmoAccountNonce> captor = ArgumentCaptor.forClass(VenmoAccountNonce.class);
    verify(fragment).postCallback(captor.capture());
    assertEquals("123456-12345-12345-a-adfa", captor.getValue().getNonce());
    assertEquals("username", captor.getValue().getDescription());
    assertEquals("username", captor.getValue().getUsername());
}
 
Example #2
Source File: SearchResultFragment.java    From aptoide-client-v8 with GNU General Public License v3.0 6 votes vote down vote up
private void setupToolbar() {
  String query = viewModel.getSearchQueryModel()
      .getFinalQuery();
  if (query.isEmpty() && !noResults) {
    toolbar.setTitle(R.string.search_hint_title);
    toolbar.setTitleMarginStart(100);
  } else if (query.isEmpty()) {
    toolbar.setTitle(R.string.search_hint_title);
  } else {
    toolbar.setTitle(query);
  }

  final AppCompatActivity activity = (AppCompatActivity) getActivity();
  activity.setSupportActionBar(toolbar);
  actionBar = activity.getSupportActionBar();
  if (actionBar != null) {
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setTitle(toolbar.getTitle());
  }
}
 
Example #3
Source File: CardPlayerFragment.java    From Music-Player with GNU General Public License v3.0 6 votes vote down vote up
private void setUpRecyclerView() {
    recyclerViewDragDropManager = new RecyclerViewDragDropManager();
    final GeneralItemAnimator animator = new RefactoredDefaultItemAnimator();

    playingQueueAdapter = new PlayingQueueAdapter(
            ((AppCompatActivity) getActivity()),
            MusicPlayerRemote.getPlayingQueue(),
            MusicPlayerRemote.getPosition(),
            R.layout.item_list,
            false,
            null);
    wrappedAdapter = recyclerViewDragDropManager.createWrappedAdapter(playingQueueAdapter);

    layoutManager = new LinearLayoutManager(getActivity());

    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setAdapter(wrappedAdapter);
    recyclerView.setItemAnimator(animator);

    recyclerViewDragDropManager.attachRecyclerView(recyclerView);

    layoutManager.scrollToPositionWithOffset(MusicPlayerRemote.getPosition() + 1, 0);
}
 
Example #4
Source File: BodyElementHorizontalRule.java    From RedReader with GNU General Public License v3.0 6 votes vote down vote up
@Override
public View generateView(
		@NonNull final AppCompatActivity activity,
		@Nullable final Integer textColor,
		@Nullable final Float textSize,
		final boolean showLinkButtons) {

	final int paddingPx = General.dpToPixels(activity, 3);
	final int thicknessPx = General.dpToPixels(activity, 1);

	final View divider = new View(activity);

	final ViewGroup.MarginLayoutParams layoutParams
			= new ViewGroup.MarginLayoutParams(
					ViewGroup.LayoutParams.MATCH_PARENT,
					thicknessPx);

	layoutParams.leftMargin = paddingPx;
	layoutParams.rightMargin = paddingPx;

	divider.setBackgroundColor(Color.GRAY);
	divider.setLayoutParams(layoutParams);

	return divider;
}
 
Example #5
Source File: HtmlRawElementBlock.java    From RedReader with GNU General Public License v3.0 6 votes vote down vote up
public HtmlRawElementBlock reduce(
		@NonNull final HtmlTextAttributes activeAttributes,
		@NonNull final AppCompatActivity activity) {

	final ArrayList<HtmlRawElement> reduced = new ArrayList<>();
	final ArrayList<LinkButtonDetails> linkButtons = new ArrayList<>();

	for(final HtmlRawElement child : mChildren) {
		child.reduce(activeAttributes, activity, reduced, linkButtons);
	}

	for(final LinkButtonDetails details : linkButtons) {
		reduced.add(new HtmlRawElementLinkButton(details));
	}

	return new HtmlRawElementBlock(mBlockType, reduced);
}
 
Example #6
Source File: Venmo.java    From braintree_android with MIT License 6 votes vote down vote up
static void onActivityResult(final BraintreeFragment fragment, int resultCode, Intent data) {
    if (resultCode == AppCompatActivity.RESULT_OK) {
        fragment.sendAnalyticsEvent("pay-with-venmo.app-switch.success");
        String nonce = data.getStringExtra(EXTRA_PAYMENT_METHOD_NONCE);

        if (shouldVault(fragment.getApplicationContext()) && fragment.getAuthorization() instanceof ClientToken) {
            vault(fragment, nonce);
        } else {
            String venmoUsername = data.getStringExtra(EXTRA_USERNAME);
            VenmoAccountNonce venmoAccountNonce = new VenmoAccountNonce(nonce, venmoUsername, venmoUsername);
            fragment.postCallback(venmoAccountNonce);
        }
    } else if (resultCode == AppCompatActivity.RESULT_CANCELED) {
        fragment.sendAnalyticsEvent("pay-with-venmo.app-switch.canceled");
    }
}
 
Example #7
Source File: IconsLoaderTask.java    From candybar with Apache License 2.0 6 votes vote down vote up
@Override
protected void onPostExecute(Boolean aBoolean) {
    super.onPostExecute(aBoolean);
    if (aBoolean) {
        if (mHome == null) return;
        if (mContext.get() == null) return;

        FragmentManager fm = ((AppCompatActivity) mContext.get()).getSupportFragmentManager();
        if (fm == null) return;

        Fragment fragment = fm.findFragmentByTag("home");
        if (fragment == null) return;

        HomeListener listener = (HomeListener) fragment;
        listener.onHomeDataUpdated(mHome);
    }
}
 
Example #8
Source File: MovieDetailsFragment.java    From MovieGuide with MIT License 6 votes vote down vote up
private void setToolbar() {
    collapsingToolbar.setContentScrimColor(ContextCompat.getColor(getContext(), R.color.colorPrimary));
    collapsingToolbar.setTitle(getString(R.string.movie_details));
    collapsingToolbar.setCollapsedTitleTextAppearance(R.style.CollapsedToolbar);
    collapsingToolbar.setExpandedTitleTextAppearance(R.style.ExpandedToolbar);
    collapsingToolbar.setTitleEnabled(true);

    if (toolbar != null) {
        ((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);

        ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    } else {
        // Don't inflate. Tablet is in landscape mode.
    }
}
 
Example #9
Source File: PayPalTwoFactorAuthUnitTest.java    From braintree_android with MIT License 6 votes vote down vote up
@Test
public void onActivityResult_callsCancelCallbackWhenBrowserSwitchIsCancelled() {
    BraintreeFragment braintreeFragment = mMockFragmentBuilder.build();

    Intent intent = mock(Intent.class);
    Uri uri = mock(Uri.class);
    PayPalAccountNonce nonce = mock(PayPalAccountNonce.class);

    when(uri.getHost()).thenReturn("cancel");
    when(intent.getData()).thenReturn(uri);
    mockStatic(PayPalTwoFactorAuthSharedPreferences.class);
    when(PayPalTwoFactorAuthSharedPreferences.getPersistedPayPalAccountNonce(braintreeFragment)).thenReturn(nonce);

    PayPalTwoFactorAuth.onActivityResult(braintreeFragment, AppCompatActivity.RESULT_OK, intent);

    verify(braintreeFragment).sendAnalyticsEvent("paypal-two-factor.browser-switch.canceled");
    verify(braintreeFragment).postCancelCallback(BraintreeRequestCodes.PAYPAL_TWO_FACTOR_AUTH);
}
 
Example #10
Source File: MaterialDatePickerTestUtils.java    From material-components-android with Apache License 2.0 6 votes vote down vote up
public static MaterialDatePicker<Long> showDatePicker(
    ActivityTestRule<? extends AppCompatActivity> activityTestRule,
    int themeResId,
    CalendarConstraints calendarConstraints) {
  FragmentManager fragmentManager = activityTestRule.getActivity().getSupportFragmentManager();
  String tag = "Date DialogFragment";

  MaterialDatePicker<Long> dialogFragment =
      MaterialDatePicker.Builder.datePicker()
          .setCalendarConstraints(calendarConstraints)
          .setTheme(themeResId)
          .build();
  dialogFragment.show(fragmentManager, tag);
  InstrumentationRegistry.getInstrumentation().waitForIdleSync();
  return dialogFragment;
}
 
Example #11
Source File: VenmoUnitTest.java    From braintree_android with MIT License 6 votes vote down vote up
@Test
public void onActivityResult_withFailedVaultCall_sendsAnalyticsEvent() throws InvalidArgumentException {
    Configuration configuration = getConfigurationFromFixture();

    Authorization clientToken = Authorization.fromString(stringFromFixture("base_64_client_token.txt"));

    disableSignatureVerification();
    BraintreeFragment fragment = new MockFragmentBuilder()
            .context(VenmoInstalledContextFactory.venmoInstalledContext(true, RuntimeEnvironment.application))
            .configuration(configuration)
            .authorization(clientToken)
            .sessionId("session-id")
            .errorResponse(new AuthorizationException("Bad fingerprint"))
            .build();

    Venmo.authorizeAccount(fragment, true);

    Intent responseIntent = new Intent()
            .putExtra(Venmo.EXTRA_PAYMENT_METHOD_NONCE, "nonce");
    Venmo.onActivityResult(fragment, AppCompatActivity.RESULT_OK, responseIntent);

    verify(fragment).sendAnalyticsEvent(endsWith("pay-with-venmo.vault.failed"));
}
 
Example #12
Source File: NavigationDrawerFragment.java    From bitmask_android with GNU General Public License v3.0 5 votes vote down vote up
private ActionBar setupActionBar() {
    AppCompatActivity activity = (AppCompatActivity) getActivity();
    activity.setSupportActionBar(toolbar);
    final ActionBar actionBar = activity.getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setHomeButtonEnabled(true);
    actionBar.setDisplayShowTitleEnabled(true);
    return actionBar;
}
 
Example #13
Source File: PostPropertiesDialog.java    From RedReader with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void prepare(AppCompatActivity context, LinearLayout items) {

	final RedditPost post = getArguments().getParcelable("post");

	items.addView(propView(context, R.string.props_title, StringEscapeUtils.unescapeHtml4(post.title.trim()), true));
	items.addView(propView(context, R.string.props_author, post.author, false));
	items.addView(propView(context, R.string.props_url, StringEscapeUtils.unescapeHtml4(post.getUrl()), false));
	items.addView(propView(context, R.string.props_created, RRTime.formatDateTime(post.created_utc * 1000, context), false));

	if(post.edited instanceof Long) {
		items.addView(propView(context, R.string.props_edited, RRTime.formatDateTime((Long) post.edited * 1000, context), false));
	} else {
		items.addView(propView(context, R.string.props_edited, R.string.props_never, false));
	}

	items.addView(propView(context, R.string.props_subreddit, post.subreddit, false));
	items.addView(propView(context, R.string.props_score, String.valueOf(post.score), false));
	items.addView(propView(context, R.string.props_num_comments, String.valueOf(post.num_comments), false));

	if(post.selftext != null && post.selftext.length() > 0) {
		items.addView(propView(context, R.string.props_self_markdown, StringEscapeUtils.unescapeHtml4(post.selftext), false));

		if(post.selftext_html != null) {
			items.addView(propView(
					context,
					R.string.props_self_html,
					StringEscapeUtils.unescapeHtml4(post.selftext_html),
					false));
		}
	}
}
 
Example #14
Source File: IntroController.java    From MusicPlayer with GNU General Public License v3.0 5 votes vote down vote up
private void initBackStack(AppCompatActivity activity, Bundle savedInstanceState) {
    FragmentManager fm = activity.getSupportFragmentManager();
    mNavigationController = FragmentNavigationController.navigationController(fm, R.id.back_wall_container);
    mNavigationController.setAbleToPopRoot(true);
    mNavigationController.setPresentStyle(PRESENT_STYLE_DEFAULT);
    mNavigationController.setDuration(250);
    mNavigationController.setInterpolator(new AccelerateDecelerateInterpolator());
    mNavigationController.presentFragment(new IntroStepOneFragment());
    // mNavigationController.presentFragment(new MainFragment());
}
 
Example #15
Source File: DemoFragment.java    From material-components-android with Apache License 2.0 5 votes vote down vote up
private void initDemoActionBar() {
  if (shouldShowDefaultDemoActionBar()) {
    AppCompatActivity activity = (AppCompatActivity) getActivity();
    activity.setSupportActionBar(toolbar);
    setDemoActionBarTitle(activity.getSupportActionBar());
  } else {
    toolbar.setVisibility(View.GONE);
  }
}
 
Example #16
Source File: SnapshotLabelDetailsFragment.java    From science-journal with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
  inflater.inflate(R.menu.menu_sensor_item_label_details, menu);

  ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
  if (actionBar != null) {
    actionBar.setTitle(
        getActivity().getResources().getString(R.string.snapshot_label_details_title));
  }

  super.onCreateOptionsMenu(menu, inflater);
}
 
Example #17
Source File: CountryPicker.java    From country-picker-android with MIT License 5 votes vote down vote up
public void showDialog(@NonNull AppCompatActivity activity) {
  if (countries == null || countries.isEmpty()) {
    throw new IllegalArgumentException(context.getString(R.string.error_no_countries_found));
  } else {
    activity.getLifecycle().addObserver(this);
    dialog = new Dialog(activity);
    View dialogView = activity.getLayoutInflater().inflate(R.layout.country_picker, null);
    initiateUi(dialogView);
    setCustomStyle(dialogView);
    setSearchEditText();
    setupRecyclerView(dialogView);
    dialog.setContentView(dialogView);
    if (dialog.getWindow() != null) {
      WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
      params.width = LinearLayout.LayoutParams.MATCH_PARENT;
      params.height = LinearLayout.LayoutParams.MATCH_PARENT;
      dialog.getWindow().setAttributes(params);
      if (theme == THEME_NEW) {
        Drawable background =
            ContextCompat.getDrawable(context, R.drawable.ic_dialog_new_background);
        if (background != null) {
          background.setColorFilter(
              new PorterDuffColorFilter(backgroundColor, PorterDuff.Mode.SRC_ATOP));
        }
        rootView.setBackgroundDrawable(background);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
      }
    }
    dialog.show();
  }
}
 
Example #18
Source File: ContextUtilsTest.java    From material-components-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithContextWrapper() {
  ApplicationProvider.getApplicationContext().setTheme(R.style.Theme_AppCompat);
  AppCompatActivity appCompatActivity = Robolectric.setupActivity(AppCompatActivity.class);
  ContextWrapper contextWrapper = new ContextWrapper(appCompatActivity);
  Activity activity = ContextUtils.getActivity(contextWrapper);
  Assert.assertNotNull(activity);
}
 
Example #19
Source File: ControllerColorPickerFragment.java    From Bluefruit_LE_Connect_Android_V2 with MIT License 5 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    AppCompatActivity activity = (AppCompatActivity) getActivity();
    if (activity != null) {
        ActionBar actionBar = activity.getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle(R.string.colorpicker_title);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }
}
 
Example #20
Source File: MainFragment.java    From Bluefruit_LE_Connect_Android_V2 with MIT License 5 votes vote down vote up
private void setActionBarTitle(String title) {
    AppCompatActivity activity = ((AppCompatActivity) getActivity());
    if (activity != null) {
        ActionBar actionBar = activity.getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle(title);
            actionBar.setDisplayHomeAsUpEnabled(false);     // Don't show caret for MainFragment
        }
    }
}
 
Example #21
Source File: BraintreeFragmentUnitTest.java    From braintree_android with MIT License 5 votes vote down vote up
@Test
public void onActivityResult_postsCancelCallbackWhenResultCodeIsCanceled() throws InvalidArgumentException {
    BraintreeFragment fragment = BraintreeFragment.newInstance(mAppCompatActivity, TOKENIZATION_KEY);
    fragment.addListener(new BraintreeCancelListener() {
        @Override
        public void onCancel(int requestCode) {
            assertEquals(42, requestCode);
            mCalled.set(true);
        }
    });

    fragment.onActivityResult(42, AppCompatActivity.RESULT_CANCELED, null);

    assertTrue(mCalled.get());
}
 
Example #22
Source File: MultiRedditListingRecyclerViewAdapter.java    From Infinity-For-Reddit with GNU Affero General Public License v3.0 5 votes vote down vote up
public MultiRedditListingRecyclerViewAdapter(AppCompatActivity activity, Retrofit oauthRetrofit,
                                             RedditDataRoomDatabase redditDataRoomDatabase,
                                             CustomThemeWrapper customThemeWrapper,
                                             String accessToken, String accountName) {
    mActivity = activity;
    mGlide = Glide.with(activity);
    mOauthRetrofit = oauthRetrofit;
    mRedditDataRoomDatabase = redditDataRoomDatabase;
    mAccessToken = accessToken;
    mAccountName = accountName;
    mPrimaryTextColor = customThemeWrapper.getPrimaryTextColor();
    mSecondaryTextColor = customThemeWrapper.getSecondaryTextColor();
}
 
Example #23
Source File: CallManager.java    From call_manage with MIT License 5 votes vote down vote up
/**
 * Start the auto calling on the list of contacts
 *
 * @param list          a list of contacts
 * @param context       the context
 * @param startPosition the start position from which to start calling
 */
public static void startAutoCalling(@NotNull List<Contact> list, @NotNull AppCompatActivity context, int startPosition) {
    sIsAutoCalling = true;
    sAutoCallPosition = startPosition;
    sAutoCallingContactsList = list;
    if (sAutoCallingContactsList.isEmpty()) Timber.e("No contacts in auto calling list");
    nextCall(context);
}
 
Example #24
Source File: BodyElementSpoilerButton.java    From RedReader with GNU General Public License v3.0 5 votes vote down vote up
@NonNull
@Override
protected View.OnClickListener generateOnClickListener(
		@NonNull final AppCompatActivity activity,
		@Nullable final Integer textColor,
		@Nullable final Float textSize,
		final boolean showLinkButtons) {

	return (button) -> {
		final ScrollView scrollView = new ScrollView(activity);

		final View view = mSpoilerText.generateView(
				activity,
				textColor,
				textSize,
				true);

		scrollView.addView(view);

		final ViewGroup.MarginLayoutParams layoutParams
				= (FrameLayout.LayoutParams)view.getLayoutParams();

		final int marginPx = General.dpToPixels(activity, 14);
		layoutParams.setMargins(marginPx, marginPx, marginPx, marginPx);

		final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
		builder.setView(scrollView);

		builder.setNeutralButton(
				R.string.dialog_close,
				(dialog, which) -> {
				});

		final AlertDialog alert = builder.create();
		alert.show();
	};
}
 
Example #25
Source File: SettingNestedFragment.java    From a with GNU General Public License v3.0 5 votes vote down vote up
protected void setActionBarTitle(CharSequence title) {
    if (getActivity() != null) {
        ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
        String t = StringUtils.nullToText(title);
        if (actionBar != null && !t.equals(actionBar.getTitle())) {
            actionBar.setTitle(t);
        }
    }
}
 
Example #26
Source File: HtmlRawElementStyledText.java    From RedReader with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void generate(
		@NonNull final AppCompatActivity activity,
		@NonNull final ArrayList<BodyElement> destination) {

	throw new RuntimeException("Attempt to call generate() on styled text: should be inside a block");
}
 
Example #27
Source File: UpdateManager.java    From InAppUpdater with MIT License 5 votes vote down vote up
public static UpdateManager Builder(AppCompatActivity activity) {
    if (instance == null) {
        instance = new UpdateManager(activity);
    }
    Log.d(TAG, "Instance created");
    return instance;
}
 
Example #28
Source File: HtmlRawElementBulletList.java    From RedReader with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void reduce(
		@NonNull final HtmlTextAttributes activeAttributes,
		@NonNull final AppCompatActivity activity,
		@NonNull final ArrayList<HtmlRawElement> destination,
		@NonNull final ArrayList<LinkButtonDetails> linkButtons) {

	destination.add(reduce(activeAttributes, activity, linkButtons));
}
 
Example #29
Source File: MainActivity.java    From Android-Image-Cropper with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressLint("NewApi")
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);

  if (requestCode == CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE
      && resultCode == AppCompatActivity.RESULT_OK) {
    Uri imageUri = CropImage.getPickImageResultUri(this, data);

    // For API >= 23 we need to check specifically that we have permissions to read external
    // storage,
    // but we don't know if we need to for the URI so the simplest is to try open the stream and
    // see if we get error.
    boolean requirePermissions = false;
    if (CropImage.isReadExternalStoragePermissionsRequired(this, imageUri)) {

      // request permissions and handle the result in onRequestPermissionsResult()
      requirePermissions = true;
      mCropImageUri = imageUri;
      requestPermissions(
          new String[] {Manifest.permission.READ_EXTERNAL_STORAGE},
          CropImage.PICK_IMAGE_PERMISSIONS_REQUEST_CODE);
    } else {

      mCurrentFragment.setImageUri(imageUri);
    }
  }
}
 
Example #30
Source File: MusicHelper.java    From Flute-Music-Player with Apache License 2.0 5 votes vote down vote up
public static boolean hasExternalStorageAccess(AppCompatActivity activity) {
    if(ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE)
            == PackageManager.PERMISSION_GRANTED) return true;

    ActivityCompat.requestPermissions(activity,
            new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
            STORAGE_PERMISSION_CODE);

    return false;
}