微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

android.support.v4.content.ContextCompat的实例源码

项目:materialExpansionPanel    文件Expandable.java   
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);

    expandIcon.setId(Expandableutils.ID_EXPAND_ICON);
    expandIcon.setLayoutParams(expandIconParams);
    expandIcon.setimageDrawable(expandindicator == null ? ContextCompat.getDrawable(getContext(),R.drawable.ic_down) : expandindicator);

    headerLayout.addView(expandIcon);
}
项目:AstronomyTourPadova    文件MainActivity.java   
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(),color));
    DrawableCompat.setTint(imageViewCategory.getDrawable(),color));
    DrawableCompat.setTint(imageViewAchievements.getDrawable(),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));
}
项目:leoapp-sources    文件NewSurveyDialog.java   
@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();
    }
}
项目:WeiXinRecordedDemo    文件BaseActivity.java   
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;
    }
项目:Tribe    文件PhotoRequest.java   
/**
 * 拍照
 */
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);
}
项目:BubblePagerIndicator    文件BubblePageIndicator.java   
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();
}
项目:app_secompufscar    文件ContatoAdapter.java   
@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();
    }
}
项目:ChatKeyboard-master    文件MediaGridAdapter.java   
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;
}
项目:qmui    文件HomeFragment.java   
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),R.mipmap.icon_tabbar_util_selected),"Helper",false
    );
    QMUITabSegment.Tab lab = new QMUITabSegment.Tab(
            ContextCompat.getDrawable(getContext(),R.mipmap.icon_tabbar_lab),R.mipmap.icon_tabbar_lab_selected),"Lab",false
    );
    mTabSegment.addTab(component)
            .addTab(util)
            .addTab(lab);
}
项目:leoapp-sources    文件ChatActivity.java   
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);
            }
        });
    }
}
项目:LoginConcept    文件AuthAdapter.java   
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,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();
}
项目:SmartHealthCare_AmbulanceApp    文件AbsRuntimePermission.java   
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,requestCode);
        }
    } else {
        onPermissionsGranted(requestCode);
    }
}
项目:gigreminder    文件ConcertDetailsActivity.java   
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);
}
项目:AdaptationX-android    文件EasyPermissions.java   
/**
 * 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;
}
项目:Hands-On-Android-UI-Development    文件AttachmentPagerFragment.java   
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);
}
项目:Android-AudioRecorder-App    文件ColorPalette.java   
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),R.color.md_purple_500),R.color.md_deep_purple_500),R.color.md_indigo_500),R.color.md_blue_500),R.color.md_light_blue_500),R.color.md_cyan_500),R.color.md_teal_500),R.color.md_green_500),R.color.md_light_green_500),R.color.md_lime_500),R.color.md_yellow_500),R.color.md_Amber_500),R.color.md_orange_500),R.color.md_deep_orange_500),R.color.md_brown_500),R.color.md_blue_grey_500),R.color.md_grey_500),R.color.av_color5)
  };
}
项目:cwac-crossport    文件ShadowDrawableWrapper.java   
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);
}
项目:SimpleBible    文件VersionSelectionRecyclerViewAdapter.java   
@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());
        }
    });
}
项目:SensorTag-Accelerometer    文件MainActivity.java   
@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();
}
项目:Styleabletoast    文件Styleabletoast.java   
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);
}
项目:AcademApp    文件SplashPageActivity.java   
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
            );
        }
    }
}
项目:GitHub    文件Connector.java   
/**
 * 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;
}
项目:Matrix-Calculator-for-Android    文件AboutMe.java   
@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);

}
项目:MyRepository    文件MainActivity.java   
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();
    }

}
项目:Remindy    文件ListAttachmentViewHolder.java   
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);
}
项目:GitHub    文件LoginActivity.java   
@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);
    }
}
项目:OpenVideoCall-Android    文件BaseActivity.java   
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;
}
项目:SmartRefreshLayout    文件FunGameBattleCityStyleActivity.java   
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));
    }
}
项目:LiuAGeAndroid    文件PhotobrowserActivity.java   
/**
 * 判断有没有保存权限,有则保存,没有则申请权限
 */
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());
    }
}
项目:StretchView    文件RightSampleActivity.java   
@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,false));
        }

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

        }

        @Override
        public int getItemCount() {
            return 10;
        }
    });
}
项目:Expert-Android-Programming    文件FriendFacebookActivity.java   
@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();
}
项目:LoginConcept    文件AuthFragment.java   
@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;
    }
}
项目:WeatherAlarmClock    文件RepeatActivity.java   
@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));
    }
}
项目:GitHub    文件MainActivity.java   
@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");
}
项目:android-mvp-interactor-architecture    文件BaseActivity.java   
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();
}
项目:Hitalk    文件XEditText.java   
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],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,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()});
    }
}
项目:Remindy    文件ProgrammedOneTiMetaskViewHolder.java   
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);
}
项目:MegviiFacepp-Android-SDK    文件FaceppActionActivity.java   
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,EXTERNAL_STORAGE_REQ_AUdio_CODE);
        } else
            startRecord();
    } else
        startRecord();
}
项目:MDRXL    文件GeraltWomanActivity.java   
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(),appBarLayout.getWidth());
    animator.setDuration(TRANSITION_DURATION);
    toolbarImageView.setVisibility(View.VISIBLE);
    animator.start();
}
项目:ITagAntiLost    文件DevicesAdapter.java   
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);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。