Java Code Examples for android.support.v4.content.ContextCompat

The following are top voted examples for showing how to use android.support.v4.content.ContextCompat. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: materialExpansionPanel   File: Expandable.java   Source Code and License 7 votes vote down vote up
private void initExpandIcon(RelativeLayout headerLayout) {
    expandIcon = new ImageView(getContext());

    int margin = (int) getContext().getResources().getDimension(R.dimen.icon_margin);

    RelativeLayout.LayoutParams expandIconParams = new RelativeLayout.LayoutParams((int) getResources().getDimension(R.dimen.expand_drawable_size), (int) getResources().getDimension(R.dimen.expand_drawable_size));

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        expandIconParams.addRule(RelativeLayout.ALIGN_PARENT_END);
    } else {
        expandIconParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
    }
    expandIconParams.addRule(RelativeLayout.CENTER_VERTICAL);
    expandIconParams.setMargins(margin, margin, margin, margin);

    expandIcon.setId(ExpandableUtils.ID_EXPAND_ICON);
    expandIcon.setLayoutParams(expandIconParams);
    expandIcon.setImageDrawable(expandIndicator == null ? ContextCompat.getDrawable(getContext(), R.drawable.ic_down) : expandIndicator);

    headerLayout.addView(expandIcon);
}
 
Example 2
Project: AstronomyTourPadova   File: MainActivity.java   Source Code and License 6 votes vote down vote up
private void activateMainIcons(boolean enabled) {
    
    Integer color = R.color.colorPrimary;
    if (!enabled) {
        color = R.color.colorSilver;
    }
    
    ImageView imageViewShowList = (ImageView) findViewById(R.id.imageViewShowList);
    ImageView imageViewShowMap = (ImageView) findViewById(R.id.imageViewShowMap);
    ImageView imageViewCategory = (ImageView) findViewById(R.id.imageViewShowCategories);
    ImageView imageViewAchievements = (ImageView) findViewById(R.id.imageViewAchievements);
    TextView textViewShowList = (TextView) findViewById(R.id.textViewShowList);
    TextView textViewShowMap = (TextView) findViewById(R.id.textViewShowMap);
    TextView textViewCategory = (TextView) findViewById(R.id.textViewShowCategories);
    TextView textViewShowAchievements = (TextView) findViewById(R.id.textViewShowAchievements);
    DrawableCompat.setTint(imageViewShowList.getDrawable(), ContextCompat.getColor(this, color));
    DrawableCompat.setTint(imageViewShowMap.getDrawable(), ContextCompat.getColor(this, color));
    DrawableCompat.setTint(imageViewCategory.getDrawable(), ContextCompat.getColor(this, color));
    DrawableCompat.setTint(imageViewAchievements.getDrawable(), ContextCompat.getColor(this, color));
    textViewShowList.setTextColor(ContextCompat.getColor(this, color));
    textViewShowMap.setTextColor(ContextCompat.getColor(this, color));
    textViewCategory.setTextColor(ContextCompat.getColor(this, color));
    textViewShowAchievements.setTextColor(ContextCompat.getColor(this, color));
}
 
Example 3
Project: leoapp-sources   File: NewSurveyDialog.java   Source Code and License 6 votes vote down vote up
@Override
protected void onPostExecute(Boolean b) {
    if (b) {
        dismiss();
        Toast.makeText(Utils.getContext(), "Umfrage erfolgreich erstellt", Toast.LENGTH_LONG).show();
    } else {
        final Snackbar snackbar = Snackbar.make(findViewById(R.id.wrapper), "Es ist etwas schiefgelaufen, versuche es später erneut", Snackbar.LENGTH_SHORT);
        snackbar.setActionTextColor(ContextCompat.getColor(getContext(), R.color.colorPrimary));
        snackbar.setAction(getContext().getString(R.string.dismiss), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                snackbar.dismiss();
            }
        });
        snackbar.show();
    }
}
 
Example 4
Project: WeiXinRecordedDemo   File: BaseActivity.java   Source Code and License 6 votes vote down vote up
public TextView showProgressDialog() {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(false);
        View view = View.inflate(this, R.layout.dialog_loading, null);
        builder.setView(view);
        ProgressBar pb_loading = (ProgressBar) view.findViewById(R.id.pb_loading);
        TextView tv_hint = (TextView) view.findViewById(R.id.tv_hint);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            pb_loading.setIndeterminateTintList(ContextCompat.getColorStateList(this, R.color.dialog_pro_color));
        }
        tv_hint.setText("视频编译中");
        progressDialog = builder.create();
        progressDialog.show();

        return tv_hint;
    }
 
Example 5
Project: Tribe   File: PhotoRequest.java   Source Code and License 6 votes vote down vote up
/**
 * 拍照
 */
private void takePhoto() {
    //在每次拍照做权限的判断,防止出现权限不全而获取不到图像
    if (ContextCompat.checkSelfPermission(mActivity,
            Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
            || ContextCompat.checkSelfPermission(mActivity,
            Manifest.permission.CAMERA)
            != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    Intent takeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.N){
        mPhotoUri = get24MediaFileUri(TYPE_TAKE_PHOTO);
        takeIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    }else {
        mPhotoUri = getMediaFileUri(TYPE_TAKE_PHOTO);
    }
    takeIntent.putExtra(MediaStore.EXTRA_OUTPUT, mPhotoUri);
    mActivity.startActivityForResult(takeIntent, COOD_TAKE_PHOTO);
}
 
Example 6
Project: BubblePagerIndicator   File: BubblePageIndicator.java   Source Code and License 6 votes vote down vote up
public BubblePageIndicator(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    if (isInEditMode()) return;

    //Load defaults from resources
    final Resources res = getResources();
    final int defaultPageColor = ContextCompat.getColor(context, R.color.default_bubble_indicator_page_color);
    final int defaultFillColor = ContextCompat.getColor(context, R.color.default_bubble_indicator_fill_color);
    final float defaultRadius = res.getDimension(R.dimen.default_bubble_indicator_radius);

    //Retrieve styles attributes
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.BubblePageIndicator, defStyle, 0);

    paintPageFill.setStyle(Style.FILL);
    paintPageFill.setColor(a.getColor(R.styleable.BubblePageIndicator_pageColor, defaultPageColor));
    paintFill.setStyle(Style.FILL);
    paintFill.setColor(a.getColor(R.styleable.BubblePageIndicator_fillColor, defaultFillColor));
    radius = a.getDimension(R.styleable.BubblePageIndicator_radius, defaultRadius);
    marginBetweenCircles = a.getDimension(R.styleable.BubblePageIndicator_marginBetweenCircles, radius);

    a.recycle();
}
 
Example 7
Project: app_secompufscar   File: ContatoAdapter.java   Source Code and License 6 votes vote down vote up
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    try {
        Pessoa.Contato contato = contatoList.get(position);
        switch (contato.getTipo().toLowerCase()) {
            case "facebook":
                holder.tipo_contato_image.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_facebook));
                break;
            case "twitter":
                holder.tipo_contato_image.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_twitter));
                break;
            case "linkedin":
                holder.tipo_contato_image.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_linkedin));
                break;
            case "github":
                holder.tipo_contato_image.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_github));
                break;
            default:
                holder.tipo_contato_image.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_outro));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 8
Project: ChatKeyboard-master   File: MediaGridAdapter.java   Source Code and License 6 votes vote down vote up
public View getView(final int position, View convertView, ViewGroup parent) {
    ViewHolder viewHolder;
    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.media_item, parent, false);
        viewHolder = new ViewHolder(convertView);
        convertView.setTag(viewHolder);
    } else {
        viewHolder = (ViewHolder) convertView.getTag();
    }
    viewHolder.tvText.setCompoundDrawablesWithIntrinsicBounds(null, ContextCompat.getDrawable(mContext, getItem(position).getDrawableId()), null, null);
    viewHolder.tvText.setText(getItem(position).getText());

    convertView.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            getItem(position).getMediaListener().onMediaClick(getItem(position).getId());
        }
    });

    return convertView;
}
 
Example 9
Project: qmui   File: HomeFragment.java   Source Code and License 6 votes vote down vote up
private void initTabs() {
    int normalColor = QMUIResHelper.getAttrColor(getActivity(), R.attr.qmui_config_color_gray_6);
    int selectColor = QMUIResHelper.getAttrColor(getActivity(), R.attr.qmui_config_color_blue);
    mTabSegment.setDefaultNormalColor(normalColor);
    mTabSegment.setDefaultSelectedColor(selectColor);
    QMUITabSegment.Tab component = new QMUITabSegment.Tab(
            ContextCompat.getDrawable(getContext(), R.mipmap.icon_tabbar_component),
            ContextCompat.getDrawable(getContext(), R.mipmap.icon_tabbar_component_selected),
            "Components", false
    );
    QMUITabSegment.Tab util = new QMUITabSegment.Tab(
            ContextCompat.getDrawable(getContext(), R.mipmap.icon_tabbar_util),
            ContextCompat.getDrawable(getContext(), R.mipmap.icon_tabbar_util_selected),
            "Helper", false
    );
    QMUITabSegment.Tab lab = new QMUITabSegment.Tab(
            ContextCompat.getDrawable(getContext(), R.mipmap.icon_tabbar_lab),
            ContextCompat.getDrawable(getContext(), R.mipmap.icon_tabbar_lab_selected),
            "Lab", false
    );
    mTabSegment.addTab(component)
            .addTab(util)
            .addTab(lab);
}
 
Example 10
Project: leoapp-sources   File: ChatActivity.java   Source Code and License 6 votes vote down vote up
private void initToolbar() {
    Toolbar toolbar = findViewById(R.id.actionBarChat);
    toolbar.setTitleTextColor(ContextCompat.getColor(getApplicationContext(), android.R.color.white));
    toolbar.setTitle(cname);
    setSupportActionBar(toolbar);
    getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_arrow_left);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);
    if (ctype != Chat.ChatType.PRIVATE && Utils.getController().getMessengerDatabase().userInChat(Utils.getUserID(), cid)) {
        toolbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(getApplicationContext(), ChatEditActivity.class)
                        .putExtra("cid", cid)
                        .putExtra("cname", cname), 1);
            }
        });
    }
}
 
Example 11
Project: LoginConcept   File: AuthAdapter.java   Source Code and License 6 votes vote down vote up
private void shiftSharedElements(float pageOffsetX, boolean forward){
    final Context context=pager.getContext();
    //since we're clipping the page, we have to adjust the shared elements
    AnimatorSet shiftAnimator=new AnimatorSet();
    for(View view:sharedElements){
        float translationX=forward?pageOffsetX:-pageOffsetX;
        float temp=view.getWidth()/3f;
        translationX-=forward?temp:-temp;
        ObjectAnimator shift=ObjectAnimator.ofFloat(view,View.TRANSLATION_X,0,translationX);
        shiftAnimator.playTogether(shift);
    }

    int color=ContextCompat.getColor(context,forward?R.color.color_logo_sign_up:R.color.color_logo_log_in);
    DrawableCompat.setTint(sharedElements.get(0).getDrawable(),color);
    //scroll the background by x
    int offset=authBackground.getWidth()/2;
    ObjectAnimator scrollAnimator=ObjectAnimator.ofInt(authBackground,"scrollX",forward?offset:-offset);
    shiftAnimator.playTogether(scrollAnimator);
    shiftAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
    shiftAnimator.setDuration(pager.getResources().getInteger(R.integer.duration)/2);
    shiftAnimator.start();
}
 
Example 12
Project: SmartHealthCare_AmbulanceApp   File: AbsRuntimePermission.java   Source Code and License 6 votes vote down vote up
public void requestAppPermissions(final String[]requestedPermissions, final int stringId, final int requestCode) {
    mErrorString.put(requestCode, stringId);

    int permissionCheck = PackageManager.PERMISSION_GRANTED;
    boolean showRequestPermissions = false;
    for(String permission: requestedPermissions) {
        permissionCheck = permissionCheck + ContextCompat.checkSelfPermission(this, permission);
        showRequestPermissions = showRequestPermissions || ActivityCompat.shouldShowRequestPermissionRationale(this, permission);
    }

    if (permissionCheck!=PackageManager.PERMISSION_GRANTED) {
        if(showRequestPermissions) {
            Snackbar.make(findViewById(android.R.id.content), stringId, Snackbar.LENGTH_INDEFINITE).setAction("GRANT", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ActivityCompat.requestPermissions(AbsRuntimePermission.this, requestedPermissions, requestCode);
                }
            }).show();
        } else {
            ActivityCompat.requestPermissions(this, requestedPermissions, requestCode);
        }
    } else {
        onPermissionsGranted(requestCode);
    }
}
 
Example 13
Project: gigreminder   File: ConcertDetailsActivity.java   Source Code and License 6 votes vote down vote up
private void fillViews(Optional<Concert> optional) {
    if (!optional.isPresent()) {
        return;
    }

    Concert concert = optional.getValue();
    String artistName = concert.getArtist().getName();

    collapsingToolbar.setTitle(artistName);
    collapsingToolbar.setExpandedTitleColor(
            ContextCompat.getColor(this, android.R.color.transparent));
    artistTextView.setText(artistName);

    String placeText = String.format("%s, %s",
            concert.getLocation().getName(), concert.getPlace());
    placeTextView.setText(placeText);

    dateTextView.setText(makeDateString(concert));

    imageLoader.loadConcertBackdrop(this, concert, backdropImageView);
}
 
Example 14
Project: AdaptationX-android   File: EasyPermissions.java   Source Code and License 6 votes vote down vote up
/**
 * Check if the calling context has a set of permissions.
 *
 * @param context
 *         the calling context.
 * @param perms
 *         one ore more permissions, such as {@code android.Manifest.permission.CAMERA}.
 * @return true if all permissions are already granted, false if at least one permission is not yet granted.
 */
public static boolean hasPermissions(@NonNull Context context, @NonNull String... perms) {
    // Always return true for SDK < M, let the system deal with the permissions
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        Log.w(TAG, "hasPermissions: API version < M, returning true by default");
        return true;
    }

    for (String perm : perms) {
        boolean hasPerm = (ContextCompat.checkSelfPermission(context, perm) ==
                PackageManager.PERMISSION_GRANTED);
        if (!hasPerm) {
            return false;
        }
    }

    return true;
}
 
Example 15
Project: Hands-On-Android-UI-Development   File: AttachmentPagerFragment.java   Source Code and License 6 votes vote down vote up
public void onAttachClick() {
    final int permissionStatus = ContextCompat.checkSelfPermission(
            getContext(),
            Manifest.permission.READ_EXTERNAL_STORAGE
    );

    if (permissionStatus != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(
                getActivity(),
                new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                REQUEST_ATTACH_PERMISSION
        );

        return;
    }

    final Intent attach = new Intent(Intent.ACTION_GET_CONTENT)
            .addCategory(Intent.CATEGORY_OPENABLE)
            .setType("*/*");

    startActivityForResult(attach, REQUEST_ATTACH_FILE);
}
 
Example 16
Project: Android-AudioRecorder-App   File: ColorPalette.java   Source Code and License 6 votes vote down vote up
public static int[] getBaseColors(Context context) {
  return new int[] {
      ContextCompat.getColor(context, R.color.md_red_500),
      ContextCompat.getColor(context, R.color.md_pink_500),
      ContextCompat.getColor(context, R.color.md_purple_500),
      ContextCompat.getColor(context, R.color.md_deep_purple_500),
      ContextCompat.getColor(context, R.color.md_indigo_500),
      ContextCompat.getColor(context, R.color.md_blue_500),
      ContextCompat.getColor(context, R.color.md_light_blue_500),
      ContextCompat.getColor(context, R.color.md_cyan_500),
      ContextCompat.getColor(context, R.color.md_teal_500),
      ContextCompat.getColor(context, R.color.md_green_500),
      ContextCompat.getColor(context, R.color.md_light_green_500),
      ContextCompat.getColor(context, R.color.md_lime_500),
      ContextCompat.getColor(context, R.color.md_yellow_500),
      ContextCompat.getColor(context, R.color.md_amber_500),
      ContextCompat.getColor(context, R.color.md_orange_500),
      ContextCompat.getColor(context, R.color.md_deep_orange_500),
      ContextCompat.getColor(context, R.color.md_brown_500),
      ContextCompat.getColor(context, R.color.md_blue_grey_500),
      ContextCompat.getColor(context, R.color.md_grey_500),
      ContextCompat.getColor(context, R.color.av_color5)
  };
}
 
Example 17
Project: cwac-crossport   File: ShadowDrawableWrapper.java   Source Code and License 6 votes vote down vote up
public ShadowDrawableWrapper(Context context, Drawable content, float radius,
          float shadowSize, float maxShadowSize) {
  super(content);

  mShadowStartColor = ContextCompat.getColor(context, R.color.design_fab_shadow_start_color);
  mShadowMiddleColor = ContextCompat.getColor(context, R.color.design_fab_shadow_mid_color);
  mShadowEndColor = ContextCompat.getColor(context, R.color.design_fab_shadow_end_color);

  mCornerShadowPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG);
  mCornerShadowPaint.setStyle(Paint.Style.FILL);
  mCornerRadius = Math.round(radius);
  mContentBounds = new RectF();
  mEdgeShadowPaint = new Paint(mCornerShadowPaint);
  mEdgeShadowPaint.setAntiAlias(false);
  setShadowSize(shadowSize, maxShadowSize);
}
 
Example 18
Project: SimpleBible   File: VersionSelectionRecyclerViewAdapter.java   Source Code and License 6 votes vote down vote up
@Override
public void onBindViewHolder(final VersionSelectionViewHolder holder, int position) {
    TextView contentView = holder.getContentView();
    if (contentView == null) {
        return;
    }

    holder.setItem(mValues.get(position));
    contentView.setText(mValues.get(position).getDisplayText());

    boolean currentIsSelected = CurrentSelected.getVersion() != null && CurrentSelected.getVersion().getId().equals(mValues.get(position).getId());

    contentView.setTextColor(ContextCompat.getColor(contentView.getContext(), currentIsSelected ? R.color.primary : R.color.primary_text));
    contentView.setTypeface(null, currentIsSelected ? Typeface.BOLD : Typeface.NORMAL);

    holder.itemView.setOnClickListener(v -> {
        if (mListener != null) {
            // Notify the active callbacks interface (the activity, if the
            // fragment is attached to one) that an item has been selected.
            mListener.onVersionSelected(holder.getItem());
        }
    });
}
 
Example 19
Project: SensorTag-Accelerometer   File: MainActivity.java   Source Code and License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mSwipeContainer = (SwipeRefreshLayout) findViewById(R.id.swipeContainer);
    mSwipeContainer.setEnabled(false);
    mSwipeContainer.setColorSchemeColors(ContextCompat.getColor(this, R.color.colorAccent));

    // exit if the device doesn't have BLE
    if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
        Toast.makeText(this, R.string.no_ble, Toast.LENGTH_SHORT).show();
        finish();
    }

    // load ScanFragment
    mFragmentManager = getSupportFragmentManager();
    mCurrentFragment = ScanFragment.newInstance();
    mFragmentManager.beginTransaction().replace(R.id.container, mCurrentFragment).commit();
}
 
Example 20
Project: StyleableToast   File: StyleableToast.java   Source Code and License 6 votes vote down vote up
private void makeShape() {
    loadShapeAttributes();
    GradientDrawable gradientDrawable = (GradientDrawable) rootLayout.getBackground();
    gradientDrawable.setCornerRadius(cornerRadius != -1 ? cornerRadius : R.dimen.default_corner_radius);
    gradientDrawable.setStroke(strokeWidth, strokeColor);
    if (backgroundColor == 0) {
        gradientDrawable.setColor(ContextCompat.getColor(context, R.color.defaultBackgroundColor));
    } else {
        gradientDrawable.setColor(backgroundColor);
    }
    if (solidBackground) {
        gradientDrawable.setAlpha(getResources().getInteger(R.integer.fullBackgroundAlpha));
    } else {
        gradientDrawable.setAlpha(getResources().getInteger(R.integer.defaultBackgroundAlpha));
    }

    rootLayout.setBackground(gradientDrawable);
}
 
Example 21
Project: AcademApp   File: SplashPageActivity.java   Source Code and License 6 votes vote down vote up
private void checkPermissions() {
    int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);
    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
        // permission not granted
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_PHONE_STATE)) {
            // show message if u want..
            // TODO: show message why we want READ_PHONE_STATE permission
            // for now, just toast why we need permissions
            showToast("We need some permissions for this app to function properly.");
        } else {
            // request the permission here
            ActivityCompat.requestPermissions(
                    this,
                    new String[]{Manifest.permission.READ_PHONE_STATE},
                    PERMISSION_REQUEST_CODE
            );
        }
    }
}
 
Example 22
Project: GitHub   File: Connector.java   Source Code and License 6 votes vote down vote up
/**
 * Build a connection to the database. This progress will analysis the
 * litepal.xml file, and will check if the fields in LitePalAttr are valid,
 * and it will open a SQLiteOpenHelper to decide to create tables or update
 * tables or doing nothing depends on the version attributes.
 * 
 * After all the stuffs above are finished. This method will return a
 * LitePalHelper object.Notes this method could throw a lot of exceptions.
 * 
 * @return LitePalHelper object.
 * 
 * @throws org.litepal.exceptions.InvalidAttributesException
 */
private static LitePalOpenHelper buildConnection() {
	LitePalAttr litePalAttr = LitePalAttr.getInstance();
	litePalAttr.checkSelfValid();
	if (mLitePalHelper == null) {
		String dbName = litePalAttr.getDbName();
		if ("external".equalsIgnoreCase(litePalAttr.getStorage())) {
			dbName = LitePalApplication.getContext().getExternalFilesDir("") + "/databases/" + dbName;
		} else if (!"internal".equalsIgnoreCase(litePalAttr.getStorage()) && !TextUtils.isEmpty(litePalAttr.getStorage())) {
               // internal or empty means internal storage, neither or them means sdcard storage
               String dbPath = Environment.getExternalStorageDirectory().getPath() + "/" + litePalAttr.getStorage();
               dbPath = dbPath.replace("//", "/");
               if (BaseUtility.isClassAndMethodExist("android.support.v4.content.ContextCompat", "checkSelfPermission") &&
                       ContextCompat.checkSelfPermission(LitePalApplication.getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                   throw new DatabaseGenerateException(String.format(DatabaseGenerateException.EXTERNAL_STORAGE_PERMISSION_DENIED, dbPath));
               }
               File path = new File(dbPath);
               if (!path.exists()) {
                   path.mkdirs();
               }
               dbName = dbPath + "/" + dbName;
           }
		mLitePalHelper = new LitePalOpenHelper(dbName, litePalAttr.getVersion());
	}
	return mLitePalHelper;
}
 
Example 23
Project: Matrix-Calculator-for-Android   File: AboutMe.java   Source Code and License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    boolean isDark = preferences.getBoolean("DARK_THEME_KEY", false);
    if (isDark)
        setTheme(R.style.AppThemeDark_NoActionBar);
    else
        setTheme(R.style.AppTheme_NoActionBar);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.aboutme_layout);
    if (isDark)
        findViewById(R.id.relativeLayoutAbout).setBackgroundColor(ContextCompat.getColor(this, R.color.DarkcolorPrimaryDark));
    else {
        findViewById(R.id.relativeLayoutAbout).setBackgroundColor(ContextCompat.getColor(this, R.color.colorPrimaryDark));
    }
    TextView textView = (TextView) findViewById(R.id.textView3);
    String s = "Version " + BuildConfig.VERSION_NAME;
    textView.setText(s);

}
 
Example 24
Project: MyRepository   File: MainActivity.java   Source Code and License 6 votes vote down vote up
private void checkPermission() {
    //6.0申请读写sd卡权限
    if (Build.VERSION.SDK_INT >= 23) {
        //检测是否有读写权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            Log.e("没有权限","走了");
            //没有权限,检查用户是否已经设置不再提醒申请该权限
            if (!ActivityCompat.shouldShowRequestPermissionRationale
                    (this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                Toast.makeText(this, "您已禁止该权限,请到设置中打开",Toast.LENGTH_SHORT).show();
            }else {
                //申请该权限
                ActivityCompat.requestPermissions(this,
                        new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
            }

        }else
            downloadApk();
    }else {
        downloadApk();
    }

}
 
Example 25
Project: Remindy   File: ListAttachmentViewHolder.java   Source Code and License 6 votes vote down vote up
private void setUpRecyclerView() {
    List<ListItemAttachment> items = mCurrent.getItems();

    if(items.size() == 0 || items.get(items.size()-1).getText() != null)   //If no items or last item of list isn't blank, add a blank item
        items.add(new ListItemAttachment());

    mLayoutManager = new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false);
    mListItemAdapter = new ListItemAttachmentAdapter(mActivity, items, mRealTimeDataPersistence);
    mListItemAdapter.setAttachmentDataUpdatedListener(new ListItemAttachmentAdapter.AttachmentDataUpdatedListener() {
        @Override
        public void onAttachmentDataUpdated() {
            mAttachmentAdapter.triggerAttachmentDataUpdatedListener();
        }
    });

    DividerItemDecoration itemDecoration = new DividerItemDecoration(mActivity, mLayoutManager.getOrientation());
    itemDecoration.setDrawable(ContextCompat.getDrawable(mActivity, R.drawable.item_decoration_complete_line));

    mRecyclerView.setNestedScrollingEnabled(false);
    mRecyclerView.addItemDecoration(itemDecoration);
    mRecyclerView.setLayoutManager(mLayoutManager);
    mRecyclerView.setAdapter(mListItemAdapter);
}
 
Example 26
Project: GitHub   File: LoginActivity.java   Source Code and License 6 votes vote down vote up
@Override
protected void onResume() {
    super.onResume();
    //进入到这个页面,如果账号输入框为空,则账号输入框自动获得焦点,并弹出键盘
    //如果两个输入框都不为空,则登录按钮可点击
    if (!user.getText().toString().equals("") && !pass.getText().toString().equals("")) {
        user_size = true;
        pass_size = true;
        login.setEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            login.setBackground(ContextCompat.getDrawable(LoginActivity.this, R.drawable.style_btn_login));
        }
    } else if (user.getText().toString().equals("")) {
        EditTextListener.showSoftInputFromWindow(LoginActivity.this, user);
    }
}
 
Example 27
Project: OpenVideoCall-Android   File: BaseActivity.java   Source Code and License 6 votes vote down vote up
public boolean checkSelfPermission(String permission, int requestCode) {
    log.debug("checkSelfPermission " + permission + " " + requestCode);
    if (ContextCompat.checkSelfPermission(this,
            permission)
            != PackageManager.PERMISSION_GRANTED) {

        ActivityCompat.requestPermissions(this,
                new String[]{permission},
                requestCode);
        return false;
    }

    if (Manifest.permission.CAMERA.equals(permission)) {
        ((AGApplication) getApplication()).initWorkerThread();
    }
    return true;
}
 
Example 28
Project: SmartRefreshLayout   File: FunGameBattleCityStyleActivity.java   Source Code and License 5 votes vote down vote up
private void setThemeColor(int colorPrimary, int colorPrimaryDark) {
    mToolbar.setBackgroundResource(colorPrimary);
    mRefreshLayout.setPrimaryColorsId(colorPrimary, android.R.color.white);
    if (Build.VERSION.SDK_INT >= 21) {
        getWindow().setStatusBarColor(ContextCompat.getColor(this, colorPrimaryDark));
    }
}
 
Example 29
Project: LiuAGeAndroid   File: PhotoBrowserActivity.java   Source Code and License 5 votes vote down vote up
/**
 * 判断有没有保存权限,有则保存,没有则申请权限
 */
private void saveCurrentImage() {
    // 判断是否有写入SD权限
    if (ContextCompat.checkSelfPermission(mContext,
            Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        // 申请权限
        ActivityCompat.requestPermissions(mContext,
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
    } else {
        // 保存图片到相册中
        StreamUtils.saveImageToAlbum(mContext, insetPhotoBeanList.get(mIndex).getUrl());
    }
}
 
Example 30
Project: StretchView   File: RightSampleActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_right_sample);

    sv = (StretchView) findViewById(R.id.sv);
    sv.setDrawHelper(new ArcDrawHelper(sv, ContextCompat.getColor(RightSampleActivity.this, R.color.colorPrimary), 40));

    rcv = (RecyclerView) findViewById(R.id.rcv);
    rcv.setLayoutManager(new LinearLayoutManager(RightSampleActivity.this, LinearLayoutManager.HORIZONTAL, false));
    rcv.addItemDecoration(new RcvDecoration(0, (int) getResources().getDimension(R.dimen.divider_horzontal), LinearLayoutCompat.HORIZONTAL));
    rcv.setAdapter(new RecyclerView.Adapter() {
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new VH(LayoutInflater.from(RightSampleActivity.this).inflate(R.layout.item_horizontal, parent, false));
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        }

        @Override
        public int getItemCount() {
            return 10;
        }
    });
}
 
Example 31
Project: Expert-Android-Programming   File: FriendFacebookActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_friends_search);

    toolbar = (Toolbar) findViewById(R.id.toolbar1);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setTitle("Find friends on Facebook");
    toolbar.setTitleTextColor(ContextCompat.getColor(context, R.color.white));

    recyclerView = (RecyclerView) findViewById(R.id.recyclerView);


    allList = new ArrayList<>();
    allAdapter = new FriendAdapter(context, allList);
    /*
    allAdapter.setClickListener(new FriendAdapter.ClickListener() {
        @Override
        public void onItemClickListener(View v, int pos) {

        }

        @Override
        public void onFriendListener(int pos, boolean isFollowing) {

        }
    });*/

    recyclerView.setLayoutManager(new LinearLayoutManager(context));
    recyclerView.setNestedScrollingEnabled(false);
    recyclerView.setAdapter(allAdapter);

    setList();
}
 
Example 32
Project: LoginConcept   File: AuthFragment.java   Source Code and License 5 votes vote down vote up
@OnClick(R.id.root)
public void unfold(){
    if(!lock) {
        caption.setVerticalText(false);
        caption.requestLayout();
        Rotate transition = new Rotate();
        transition.setStartAngle(-90f);
        transition.setEndAngle(0f);
        transition.addTarget(caption);
        TransitionSet set=new TransitionSet();
        set.setDuration(getResources().getInteger(R.integer.duration));
        ChangeBounds changeBounds=new ChangeBounds();
        set.addTransition(changeBounds);
        set.addTransition(transition);
        TextSizeTransition sizeTransition=new TextSizeTransition();
        sizeTransition.addTarget(caption);
        set.addTransition(sizeTransition);
        set.setOrdering(TransitionSet.ORDERING_TOGETHER);
        caption.post(()->{
            TransitionManager.beginDelayedTransition(parent, set);
            caption.setTextSize(TypedValue.COMPLEX_UNIT_PX,getResources().getDimension(R.dimen.unfolded_size));
            caption.setTextColor(ContextCompat.getColor(getContext(),R.color.color_label));
            caption.setTranslationX(0);
            ConstraintLayout.LayoutParams params = getParams();
            params.rightToRight = ConstraintLayout.LayoutParams.PARENT_ID;
            params.leftToLeft = ConstraintLayout.LayoutParams.PARENT_ID;
            params.verticalBias = 0.78f;
            caption.setLayoutParams(params);
        });
        callback.show(this);
        lock=true;
    }
}
 
Example 33
Project: WeatherAlarmClock   File: RepeatActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_repeat);
    ButterKnife.bind(this);

    alarmClockLab = new AlarmClockBuilder().builderLab(0);

    tvOnce.setOnClickListener(this);
    tvWeekDay.setOnClickListener(this);
    tvEveryDay.setOnClickListener(this);
    tvWeekend.setOnClickListener(this);
    tvChoice.setOnClickListener(this);

    String repeat = alarmClockLab.repeat;
    if (repeat.equals(tvOnce.getText().toString())) {
        tvOnce.setTextColor(ContextCompat.getColor(this, R.color.colorRed_500));
    } else if (repeat.equals(tvWeekDay.getText().toString())) {
        tvWeekDay.setTextColor(ContextCompat.getColor(this, R.color.colorRed_500));
    } else if (repeat.equals(tvEveryDay.getText().toString())) {
        tvEveryDay.setTextColor(ContextCompat.getColor(this, R.color.colorRed_500));
    } else if (repeat.equals(tvWeekend.getText().toString())) {
        tvWeekend.setTextColor(ContextCompat.getColor(this, R.color.colorRed_500));
    } else if (repeat.equals(tvChoice.getText().toString())) {
        tvChoice.setTextColor(ContextCompat.getColor(this, R.color.colorRed_500));
    }
}
 
Example 34
Project: GitHub   File: MainActivity.java   Source Code and License 5 votes vote down vote up
@OnClick(R.id.customView_webView) public void showCustomWebView() {
    int accentColor = ThemeSingleton.get().widgetColor;
    if (accentColor == 0)
        accentColor = ContextCompat.getColor(this, R.color.accent);
    ChangelogDialog.create(false, accentColor)
            .show(getSupportFragmentManager(), "changelog");
}
 
Example 35
Project: android-mvp-interactor-architecture   File: BaseActivity.java   Source Code and License 5 votes vote down vote up
private void showSnackBar(String message) {
    Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content),
            message, Snackbar.LENGTH_SHORT);
    View sbView = snackbar.getView();
    TextView textView = (TextView) sbView
            .findViewById(android.support.design.R.id.snackbar_text);
    textView.setTextColor(ContextCompat.getColor(this, R.color.white));
    snackbar.show();
}
 
Example 36
Project: Hitalk   File: XEditText.java   Source Code and License 5 votes vote down vote up
private void init() {
    if (getInputType() == InputType.TYPE_CLASS_NUMBER) { // if inputType="number", it can't insert separator.
        setInputType(InputType.TYPE_CLASS_PHONE);
    }

    mTextWatcher = new MyTextWatcher();
    this.addTextChangedListener(mTextWatcher);
    mRightMarkerDrawable = getCompoundDrawables()[2];
    if (customizeMarkerEnable && mRightMarkerDrawable != null) {
        setCompoundDrawables(getCompoundDrawables()[0], getCompoundDrawables()[1],
                null, getCompoundDrawables()[3]);
        setHasNoSeparator(true);
    }
    if (mRightMarkerDrawable == null) { // didn't customize Marker
        mRightMarkerDrawable = ContextCompat.getDrawable(getContext(), R.mipmap.indicator_input_error);
        DrawableCompat.setTint(mRightMarkerDrawable, getCurrentHintTextColor());
        if (mRightMarkerDrawable != null) {
            mRightMarkerDrawable.setBounds(0, 0, mRightMarkerDrawable.getIntrinsicWidth(),
                    mRightMarkerDrawable.getIntrinsicHeight());
        }
    }

    setOnFocusChangeListener(new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            hasFocused = hasFocus;
            markerFocusChangeLogic();
            iOSFocusChangeLogic();
        }
    });

    if (iOSStyleEnable) {
        initiOSObjects();
    }
    if (disableEmoji) {
        setFilters(new InputFilter[]{new EmojiExcludeFilter()});
    }
}
 
Example 37
Project: Remindy   File: ProgrammedOneTimeTaskViewHolder.java   Source Code and License 5 votes vote down vote up
public void setData(HomeAdapter adapter, Fragment fragment, Task current, int position, boolean isSelected, boolean nextItemIsATask) {
    mAdapter = adapter;
    mFragment = fragment;
    mCurrent = current;
    mReminderPosition = position;

    mCategoryIcon.setImageResource(mCurrent.getCategory().getIconRes());

    mContainer.setBackgroundColor((isSelected ? ContextCompat.getColor(fragment.getActivity(), R.color.gray_300) : Color.TRANSPARENT ));

    mAttachmentList.setColorFilter(ContextCompat.getColor(mFragment.getActivity(), (hasAttachmentsOfType(AttachmentType.LIST) ? R.color.icons_enabled : R.color.icons_disabled)));
    mAttachmentLink.setColorFilter(ContextCompat.getColor(mFragment.getActivity(), (hasAttachmentsOfType(AttachmentType.LINK) ? R.color.icons_enabled : R.color.icons_disabled)));
    mAttachmentAudio.setColorFilter(ContextCompat.getColor(mFragment.getActivity(), (hasAttachmentsOfType(AttachmentType.AUDIO) ? R.color.icons_enabled : R.color.icons_disabled)));
    mAttachmentImage.setColorFilter(ContextCompat.getColor(mFragment.getActivity(), (hasAttachmentsOfType(AttachmentType.IMAGE) ? R.color.icons_enabled : R.color.icons_disabled)));
    mAttachmentText.setColorFilter(ContextCompat.getColor(mFragment.getActivity(), (hasAttachmentsOfType(AttachmentType.TEXT) ? R.color.icons_enabled : R.color.icons_disabled)));

    mTitle.setText(mCurrent.getTitle());
    if(!mCurrent.getDescription().isEmpty())
        mDescription.setText(mCurrent.getDescription());
    else
        mDescription.setText("");

    if(current.getReminderType() == ReminderType.ONE_TIME && current.getReminder() != null) {
        DateFormat df = SharedPreferenceUtil.getDateFormat(mFragment.getActivity());
        mDate.setText(df.formatCalendar(((OneTimeReminder)current.getReminder()).getDate()));
        mTime.setText(((OneTimeReminder)current.getReminder()).getTime().toString());
    } else {
        mDate.setText("-");
        mTime.setText("-");
    }

    mItemDecoration.setVisibility(nextItemIsATask ? View.VISIBLE : View.INVISIBLE);
}
 
Example 38
Project: MegviiFacepp-Android-SDK   File: FaceppActionActivity.java   Source Code and License 5 votes vote down vote up
private void startRecordWithPerm() {
    if (android.os.Build.VERSION.SDK_INT >= M) {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //进行权限请求
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    EXTERNAL_STORAGE_REQ_AUDIO_CODE);
        } else
            startRecord();
    } else
        startRecord();
}
 
Example 39
Project: MDRXL   File: GeraltWomanActivity.java   Source Code and License 5 votes vote down vote up
private void reveal() {
    appBarLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.colorPrimary));
    final Pair<Float, Float> center = ViewUtils.getCenter(revealImage);
    final Animator animator = ViewAnimationUtils.createCircularReveal(appBarLayout,
            center.first.intValue(), center.second.intValue(), 0, appBarLayout.getWidth());
    animator.setDuration(TRANSITION_DURATION);
    toolbarImageView.setVisibility(View.VISIBLE);
    animator.start();
}
 
Example 40
Project: ITagAntiLost   File: DevicesAdapter.java   Source Code and License 5 votes vote down vote up
DevicesAdapter(Context context, DeviceAdapterListener listener) {
  this.listener = listener;
  red = ContextCompat.getColor(context, R.color.mojo);
  green = ContextCompat.getColor(context, R.color.fern);

  connected = context.getString(R.string.status_connected);
  disconnected = context.getString(R.string.status_disconnected);
}