android.support.v4.content.ContextCompat Java Examples

The following examples show how to use android.support.v4.content.ContextCompat. 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: MainActivity.java    From renrenpay-android with Apache License 2.0 6 votes vote down vote up
/**
 * 获取权限。。有些手机很坑,明明是READ_PHONE_STATE权限,却问用户是否允许拨打电话,汗。
 */
private void getPermissions() {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        return;
    }
    List<String> sa = new ArrayList<>();
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
            != PackageManager.PERMISSION_GRANTED) {
        //申请READ_PHONE_STATE权限。。。。
        sa.add(Manifest.permission.READ_PHONE_STATE);
    }
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {
        sa.add(Manifest.permission.READ_EXTERNAL_STORAGE);
    }
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {
        sa.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }
    if (sa.size() < 1) {
        return;
    }
    ActivityCompat.requestPermissions(this, sa.toArray(new String[]{}), 1);
}
 
Example #2
Source File: MatchProgressActivity.java    From android with Apache License 2.0 6 votes vote down vote up
private void appendEvent(@DrawableRes int icon, String text, int gravity) {
  FrameLayout view = (FrameLayout) LayoutInflater.from(this)
      .inflate(R.layout.match_event, eventsLayout, false);
  TextView textView = view.findViewById(R.id.txt_match_events);
  textView.setText(text);
  Drawable drawable = ContextCompat.getDrawable(this, icon);
  drawable.setBounds(0, 0, iconSize, iconSize);
  textView.setCompoundDrawablePadding(iconPadding);
  if (gravity == GravityCompat.START) {
    textView.setCompoundDrawables(null, null, drawable, null);
  } else {
    textView.setCompoundDrawables(drawable, null, null, null);
  }
  LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) view.getLayoutParams();
  layoutParams.gravity = gravity;
  view.setLayoutParams(layoutParams);
  textView.setGravity(gravity);
  eventsLayout.addView(view, 0);
  eventsTimeline.setVisibility(View.VISIBLE);
  eventsScrollView.smoothScrollTo(0, 0);
}
 
Example #3
Source File: WearActivity.java    From pocketsphinx-android-demo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public void onCreate(Bundle state) {
    super.onCreate(state);

    // Prepare the data for UI
    captions = new HashMap<String, Integer>();
    captions.put(KWS_SEARCH, R.string.kws_caption);
    captions.put(MENU_SEARCH, R.string.menu_caption);
    captions.put(DIGITS_SEARCH, R.string.digits_caption);
    captions.put(PHONE_SEARCH, R.string.phone_caption);
    captions.put(FORECAST_SEARCH, R.string.forecast_caption);
    setContentView(R.layout.activity_main);
    ((TextView) findViewById(edu.cmu.pocketsphinx.demo.wear.R.id.caption_text))
            .setText("Preparing the recognizer");

    // Check if user has given permission to record audio
    int permissionCheck = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.RECORD_AUDIO);
    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, PERMISSIONS_REQUEST_RECORD_AUDIO);
        return;
    }
    runRecognizerSetup();
}
 
Example #4
Source File: DownloadManagerResolver.java    From FaceSlim with GNU General Public License v2.0 6 votes vote down vote up
private static AlertDialog createDialog(final Context context) {
    AppCompatTextView messageTextView = new AppCompatTextView(context);
    messageTextView.setTextSize(16f);
    messageTextView.setText(context.getString(R.string.download_manager_disabled));
    messageTextView.setPadding(50, 50, 50, 0);
    messageTextView.setTextColor(ContextCompat.getColor(context, R.color.black));
    return new AlertDialog.Builder(context)
            .setView(messageTextView)
            .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    enableDownloadManager(context);
                }
            })
            .setCancelable(false)
            .create();
}
 
Example #5
Source File: QueueActivity.java    From PainlessMusicPlayer with Apache License 2.0 6 votes vote down vote up
private void prepareViewsAndExit(@NonNull final Runnable exitAction) {
    if (!TransitionUtils.supportsActivityTransitions() ||
            (fab.getScaleX() == 0f && albumArtDim.getAlpha() == 0f)) {
        exitAction.run();
    } else {
        final boolean isLandscape = getResources().getConfiguration().orientation
                == Configuration.ORIENTATION_LANDSCAPE;
        // Landscape Now Playing has a dim, so dim the ImageView and send it
        if (isLandscape) {
            albumArtDim.setAlpha(0f);
            albumArt.setColorFilter(
                    ContextCompat.getColor(this, R.color.translucentBackground),
                    PorterDuff.Mode.SRC_ATOP);
        } else {
            // Portrait NowPlaying does not have a dim. Fade out the dim before animating.
            albumArtDim.animate().alpha(0f).setDuration(mShortAnimTime).start();
        }
        fab.animate().scaleX(0f).scaleY(0f).setDuration(mShortAnimTime)
                .setListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(final Animator animation) {
                        exitAction.run();
                    }
                }).start();
    }
}
 
Example #6
Source File: MainActivity.java    From TextThing with BSD 2-Clause "Simplified" License 6 votes vote down vote up
void themeDay() {
    themeNr = 1;
    mainView.setBackgroundColor(
            ContextCompat.getColor(getApplicationContext(), R.color.MiddleDay)
    );
    btn.setTextColor(Color.WHITE);
    contentView.setBackgroundColor(
            ContextCompat.getColor(getApplicationContext(), R.color.DarkDay)
    );
    contentView.setTextColor(
            ContextCompat.getColor(getApplicationContext(), R.color.LightDay)
    );
    if (Build.VERSION.SDK_INT >= 21) {
        getWindow().setStatusBarColor(
                ContextCompat.getColor(getApplicationContext(), R.color.LightDay)
        );
    }
    if (isMono) {
        contentView.setTypeface(Typeface.MONOSPACE);
        btn.setTypeface(Typeface.MONOSPACE);
    } else {
        contentView.setTypeface(Typeface.SANS_SERIF);
        btn.setTypeface(Typeface.SANS_SERIF);
    }
}
 
Example #7
Source File: AuthenticatorActivity.java    From Capstone-Project with MIT License 6 votes vote down vote up
private void manageBackgroundColor() {
    switch (PredatorSharedPreferences.getCurrentTheme(getApplicationContext())) {
        case LIGHT:
            relativeLayoutAuthenticator.setBackgroundColor(ContextCompat.getColor(getApplicationContext(),
                    R.color.background_color));
            break;
        case DARK:
            relativeLayoutAuthenticator.setBackgroundColor(ContextCompat.getColor(getApplicationContext(),
                    R.color.background_color_inverse));
            break;
        case AMOLED:
            relativeLayoutAuthenticator.setBackgroundColor(ContextCompat.getColor(getApplicationContext(),
                    R.color.background_color_amoled));
            break;
    }
}
 
Example #8
Source File: MainActivity.java    From MOAAP with MIT License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    Log.i(TAG, "called onCreate");
    super.onCreate(savedInstanceState);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    setContentView(R.layout.activity_main);

    if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA)
            != PackageManager.PERMISSION_GRANTED) {
        Log.i("permission", "request READ_EXTERNAL_STORAGE");
        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA);
    }else {
        Log.i("permission", "READ_EXTERNAL_STORAGE already granted");
        camera_granted = true;
    }

    mOpenCvCameraView = (CameraBridgeViewBase) findViewById(R.id.java_surface_view);
    mOpenCvCameraView.setCvCameraViewListener(this);

}
 
Example #9
Source File: MainActivity.java    From OpenWeatherPlus-Android with Apache License 2.0 6 votes vote down vote up
@Override
public void onLocationChanged(AMapLocation aMapLocation) {
    if (aMapLocation.getErrorCode() == 0) {
        ContentUtil.NOW_LON = aMapLocation.getLongitude();
        ContentUtil.NOW_LAT = aMapLocation.getLatitude();
        getNowCity(true);
        mLocationClient.onDestroy();
    } else {
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED) {
            // 没有权限
            View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.pop_loc_list, null);
            LocListWindow locListWindow = new LocListWindow(view, MATCH_PARENT, MATCH_PARENT, MainActivity.this);
            locListWindow.show();
            locListWindow.showAtLocation(tvLocation, Gravity.CENTER, 0, 0);
            if (ContentUtil.FIRST_OPEN) {
                ContentUtil.FIRST_OPEN = false;
                SpUtils.putBoolean(MainActivity.this, "first_open", false);
            }
        }
        getNowCity(true);
        mLocationClient.onDestroy();
    }
}
 
Example #10
Source File: PDFViewActivity.java    From AndroidPdfViewerV1 with Apache License 2.0 6 votes vote down vote up
@OptionsItem(R.id.pickFile)
void pickFile() {
    int permissionCheck = ContextCompat.checkSelfPermission(this,
            READ_EXTERNAL_STORAGE);

    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(
                this,
                new String[]{READ_EXTERNAL_STORAGE},
                PERMISSION_CODE
        );

        return;
    }

    launchPicker();
}
 
Example #11
Source File: MainActivity.java    From android-base-mvp with Apache License 2.0 6 votes vote down vote up
@Override
public void showWeather(WeatherPojo weatherPojo) {

    Timber.d("show Weather %s", weatherPojo.toString());

    textview_main_city.setText(weatherPojo.getName());
    textView_main_current_temperature.setText(String.format("%.1f°", weatherPojo.getMain().getTemp()));
    textView_main_min_max.setText(String.format("%.1f°  %.1f°", weatherPojo.getMain().getTempMin(), weatherPojo.getMain().getTempMax()));
    textView_main_conditions.setText(weatherPojo.getWeather().get(0).getDescription());
    textView_main_humidity.setText(getString(R.string.humidity) + " " + weatherPojo.getMain().getHumidity() + "%");

    String wind_suffix = getResources().getString(R.string.wind_suffix_metric);
    if (UnitLocale.getDefault().equals(UnitLocale.Imperial))
        wind_suffix = getResources().getString(R.string.wind_suffix_imperial);
    textView_main_wind.setText(getString(R.string.wind) + " " + String.valueOf(weatherPojo.getWind().getSpeed()) + wind_suffix);

    textView_main_pressure.setText(getString(R.string.pressure) + " " + weatherPojo.getMain().getPressure() + "hPa");
    imageView_main_icon.setImageDrawable(ContextCompat.getDrawable(getContext(), getIcon(weatherPojo.getWeather().get(0).getId())));
}
 
Example #12
Source File: TintableImageView.java    From ImageLetterIcon with Apache License 2.0 6 votes vote down vote up
@Override
protected void drawableStateChanged() {
    super.drawableStateChanged();
    if (mTint != null) {
        if (mTint.isStateful())
            setColorFilter(mTint.getColorForState(getDrawableState(), 0));
        else setColorFilter(mTint);
    }
    Drawable drawable = getBackground();
    if (mBackgroundTint != null && drawable != null) {
        Drawable wrap = DrawableCompat.wrap(drawable);
        wrap = wrap.mutate();

        if (mBackgroundTint.isStateful())
            DrawableCompat.setTint(wrap, ContextCompat.getColor(getContext(), mBackgroundTint.getColorForState(getDrawableState(), 0)));
        else DrawableCompat.setTintList(wrap, mBackgroundTint);

        DrawableCompat.setTintMode(wrap, PorterDuff.Mode.SRC_IN);
    }
}
 
Example #13
Source File: MainActivity.java    From Android-Example with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    tvLatitude = (TextView)findViewById(R.id.latitude);
    tvLongitude = (TextView)findViewById(R.id.longitude);

    try {
        if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ) {
            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 101);
        }
    } catch (Exception e){
        e.printStackTrace();
    }
}
 
Example #14
Source File: PBaseLoaderFragment.java    From YImagePicker with Apache License 2.0 6 votes vote down vote up
/**
 * 加载媒体文件夹
 */
protected void loadMediaSets() {
    if (getActivity() == null) {
        return;
    }
    if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQ_STORAGE);
    } else {
        //从媒体库拿到文件夹列表
        ImagePicker.provideMediaSets(getActivity(), getSelectConfig().getMimeTypes(), new MediaSetsDataSource.MediaSetProvider() {
            @Override
            public void providerMediaSets(ArrayList<ImageSet> imageSets) {
                loadMediaSetsComplete(imageSets);
            }
        });
    }
}
 
Example #15
Source File: LogoutActivity.java    From KUAS-AP-Material with MIT License 6 votes vote down vote up
@Override
public void onClick(View v) {
	if (v.getId() == R.id.button_openUrl) {
		mTracker.send(new HitBuilders.EventBuilder().setCategory("open url").setAction("click")
				.build());
		String shareData = mTitle + "\n" + mURL +
				"\n\n" + getString(R.string.send_from);
		CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
		Bitmap icon =
				BitmapFactory.decodeResource(getResources(), R.drawable.ic_share_white_24dp);
		builder.setActionButton(icon, getString(R.string.share),
				Utils.createSharePendingIntent(this, shareData));
		builder.setToolbarColor(ContextCompat.getColor(this, R.color.main_theme));
		CustomTabsIntent customTabsIntent = builder.build();
		customTabsIntent.launchUrl(this, Uri.parse(mURL));
	} else if (v.getId() == R.id.button_logout) {
		mTracker.send(new HitBuilders.EventBuilder().setCategory("logout").setAction("click")
				.build());
		clearUserData();
		startActivity(new Intent(this, LoginActivity.class));
		finish();
	}
}
 
Example #16
Source File: RegisterActivity.java    From tysq-android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 显示邮箱验证验证
 *
 * @param registerResp
 */
private void showEmailVerifyDialog(RegisterResp registerResp) {

    String content = String.format(getString(R.string.email_verify_tip_content), registerResp.getActivateEmailScore());

    new MaterialDialog.Builder(this)
            .title(getString(R.string.email_verify_tip_title))
            .content(content)
            .negativeColor(ContextCompat.getColor(this, R.color.et_tip_text_color))
            .negativeText(getString(R.string.email_verify_skip))
            .onNegative((dialog, which) -> {
                // 发送登录成功事件,会关闭 "登录"、"注册"、"忘记密码" 页
                EventBus.getDefault().post(new LoginSucEvent());
            })
            .positiveColor(ContextCompat.getColor(this, R.color.main_blue_color))
            .positiveText(getString(R.string.email_verify_verify))
            .onPositive((dialog, which) -> {

                EmailVerifyActivity
                        .startActivity(this, UserCache.getDefault().getEmail());

                // 发送登录成功事件,会关闭 "登录"、"注册"、"忘记密码" 页
                EventBus.getDefault().post(new LoginSucEvent());
            })
            .show();
}
 
Example #17
Source File: MainActivity.java    From SoftwarePilot with MIT License 6 votes vote down vote up
/**
 * Checks if there is any missing permissions, and
 * requests runtime permission if needed.
 */
private void checkAndRequestPermissions() {
    // Check for permissions
    for (String eachPermission : REQUIRED_PERMISSION_LIST) {
        if (ContextCompat.checkSelfPermission(this, eachPermission) != PackageManager.PERMISSION_GRANTED) {
            missingPermission.add(eachPermission);
        }
    }
    // Request for missing permissions
    if (missingPermission.isEmpty()) {
        startSDKRegistration();
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        showToast("Need to grant the permissions!");
        ActivityCompat.requestPermissions(this,
                missingPermission.toArray(new String[missingPermission.size()]),
                REQUEST_PERMISSION_CODE);
    }

}
 
Example #18
Source File: SwipeToDeleteCallback.java    From journaldev with MIT License 5 votes vote down vote up
SwipeToDeleteCallback(Context context) {
    mContext = context;
    mBackground = new ColorDrawable();
    backgroundColor = Color.parseColor("#b80f0a");
    mClearPaint = new Paint();
    mClearPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
    deleteDrawable = ContextCompat.getDrawable(mContext, R.drawable.ic_delete);
    intrinsicWidth = deleteDrawable.getIntrinsicWidth();
    intrinsicHeight = deleteDrawable.getIntrinsicHeight();


}
 
Example #19
Source File: BaseActivity.java    From KA27 with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Check if darktheme is in use and cache it as boolean
    if (Utils.DARKTHEME = Utils.getBoolean("darktheme", false, this)) {
        super.setTheme(getDarkTheme());
        getWindow().getDecorView().getRootView().setBackgroundColor(ContextCompat.getColor(this, R.color.black));
    }

    if (getParentViewId() != 0) setContentView(getParentViewId());
    else if (getParentView() != null) setContentView(getParentView());

    Toolbar toolbar;
    if ((toolbar = getToolbar()) != null) {
        if (Utils.DARKTHEME) toolbar.setPopupTheme(R.style.ThemeOverlay_AppCompat_Dark);
        try {
            setSupportActionBar(toolbar);
        } catch (NoClassDefFoundError e) {
            Utils.toast(e.getMessage(), this, Toast.LENGTH_LONG);
            finish();
        }
    }

    ActionBar actionBar;
    if ((actionBar = getSupportActionBar()) != null)
        actionBar.setDisplayHomeAsUpEnabled(getDisplayHomeAsUpEnabled());

    setStatusBarColor();
}
 
Example #20
Source File: BusinessHoursWeekView.java    From business-hours-picker with MIT License 5 votes vote down vote up
private void initViews(Context context, AttributeSet attrs) {

        setOrientation(VERTICAL);
        model = new LinkedList<>();
        setMinimumHeight(50);

        TypedArray array = context.getTheme()
                .obtainStyledAttributes(attrs, R.styleable.BusinessHoursWeekView, 0, 0);

        try {

            bhTextColor = array.getColor(R.styleable.BusinessHoursWeekView_bhTextColor, ContextCompat.getColor(getContext(), R.color.text_default_color));
            bhIcon = array.getDrawable(R.styleable.BusinessHoursWeekView_bhIcon);
            bhTodayIcon = array.getDrawable(R.styleable.BusinessHoursWeekView_bhTodayIcon);
            bhIconPadding = array.getInt(R.styleable.BusinessHoursWeekView_bhIconPadding, 16);
            bhTextSize = array.getInt(R.styleable.BusinessHoursWeekView_bhTextSize, 14);
            bhTextStyle = array.getInt(R.styleable.BusinessHoursWeekView_bhTextStyle, Typeface.NORMAL);
            bhTodayColor = array.getColor(R.styleable.BusinessHoursWeekView_bhTodayColor, ContextCompat.getColor(getContext(), R.color.text_default_color));
            bhTodaySize = array.getInt(R.styleable.BusinessHoursWeekView_bhTodayTextSize, 16);
            bhTodayStyle = array.getInt(R.styleable.BusinessHoursWeekView_bhTodayStyle, Typeface.BOLD);

        } finally {
            array.recycle();
        }

        model = new ArrayList<>();
        initModel();

        update();
    }
 
Example #21
Source File: MainActivity.java    From RapidSphinx with MIT License 5 votes vote down vote up
private void requestPermissions() {
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.RECORD_AUDIO},
                1);
    }
}
 
Example #22
Source File: FabSpeedDial.java    From fab-speed-dial with Apache License 2.0 5 votes vote down vote up
private ColorStateList getColorStateList(int colorRes) {
    int[][] states = new int[][]{
            new int[]{android.R.attr.state_enabled}, // enabled
            new int[]{-android.R.attr.state_enabled}, // disabled
            new int[]{-android.R.attr.state_checked}, // unchecked
            new int[]{android.R.attr.state_pressed}  // pressed
    };

    int color = ContextCompat.getColor(getContext(), colorRes);

    int[] colors = new int[]{color, color, color, color};
    return new ColorStateList(states, colors);
}
 
Example #23
Source File: BasePredictionPopupWindow.java    From autocomplete-toolbar-search-view with MIT License 5 votes vote down vote up
public BasePredictionPopupWindow(Context context, @LayoutRes int layout) {
    super(LayoutInflater.from(context).inflate(layout, null), MATCH_PARENT, MATCH_PARENT, false);

    setBackgroundDrawable(ContextCompat.getDrawable(getContentView().getContext(), R.drawable.prediction_popup_bg));
    setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
    setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
    setAnimationStyle(R.style.Animation);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        setElevation(24);
}
 
Example #24
Source File: AbsNavigationItemDescriptor.java    From material-navigation-drawer with Apache License 2.0 5 votes vote down vote up
public Drawable getActivatedBackground(Context context) {
    if (!customActivatedBackground) {
        return Utils.getActivatedDrawable(context);
    } else if (activatedBackgroundAttr != 0) {
        return Utils.getDrawableAttr(context, activatedBackgroundAttr);
    } else if (activatedBackgroundId != 0) {
        return ContextCompat.getDrawable(context, activatedBackgroundId);
    } else {
        return activatedBackground;
    }
}
 
Example #25
Source File: ExploreSelectedTitleListAdapter.java    From C9MJ with Apache License 2.0 5 votes vote down vote up
@Override
protected void convert(BaseViewHolder viewHolder, String title) {
    viewHolder.setText(R.id.tv_title, title)
            .setTextColor(R.id.tv_title, ContextCompat.getColor(mContext, R.color.color_icons))
            .addOnClickListener(R.id.cardview);
    CardView cardView = viewHolder.getView(R.id.cardview);
    cardView.setCardBackgroundColor(ContextCompat.getColor(mContext, R.color.color_primary));
}
 
Example #26
Source File: Helper.java    From AwesomeImagePicker with Apache License 2.0 5 votes vote down vote up
public static boolean checkPermissionForExternalStorage(Activity activity) {
    int result =
            ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE);
    if (result == PackageManager.PERMISSION_GRANTED) {
        return true;
    } else {
        return false;
    }
}
 
Example #27
Source File: KcaItemAdapter.java    From kcanotify_h5-master with GNU General Public License v3.0 5 votes vote down vote up
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView==null)
        convertView = inf.inflate(layout, null);
    ImageView iv = (ImageView) convertView.findViewById(R.id.setting_image_pic);
    KcaUtils.setFairyImageFromStorage(context, item.get(position), iv, IMAGE_SIZE);
    if (position == prevactive) iv.setBackground(ContextCompat.getDrawable(context, R.drawable.imagebtn_on));
    else iv.setBackground(ContextCompat.getDrawable(context, R.drawable.imagebtn_off));
    if (rescale > 0) {
        iv.getLayoutParams().width = rescale;
        iv.getLayoutParams().height = rescale;
    }
    return convertView;
}
 
Example #28
Source File: LocalContactsActivity.java    From talk-android with MIT License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_local_contacts);
    ButterKnife.inject(this);

    setSupportActionBar(toolbar);
    getSupportActionBar().setTitle(R.string.local_contacts);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    presenter = new LocalContactsPresenter(this, this);
    adapter = new ContactsAdapter(this);

    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setAdapter(adapter);

    if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_CONTACTS)) {
            MainApp.showToastMsg(R.string.record_contacts_permission_denied);
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, READ_CONTACTS_PERMISSION);
        }
    } else {
        presenter.getContacts();
    }
    searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            adapter.filterName(newText);
            return false;
        }
    });
}
 
Example #29
Source File: LoadProjectFragment.java    From BuildmLearn-Toolkit-Android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * @brief Restores the color scheme when switching from edit mode to normal mode.
 * <p/>
 * Edit mode is triggered, when the list item is long pressed.
 */
private void restoreColorScheme() {
    int primaryColor = ContextCompat.getColor(mToolkit, R.color.color_primary);
    int primaryColorDark = ContextCompat.getColor(mToolkit, R.color.color_primary_dark);
    ((AppCompatActivity) activity).getSupportActionBar().setBackgroundDrawable(new ColorDrawable(primaryColor));
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        activity.getWindow().setStatusBarColor(primaryColorDark);
        activity.getWindow().setNavigationBarColor(primaryColor);
    }
    showTemplateSelectedMenu = false;
    activity.invalidateOptionsMenu();
}
 
Example #30
Source File: UtilsApp.java    From MLManager with GNU General Public License v3.0 5 votes vote down vote up
public static Boolean checkPermissions(Activity activity) {
    Boolean res = false;
    if (ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        activity.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_READ);
    } else {
        res = true;
    }

    return res;
}