下面列出了怎么用android.graphics.drawable.ColorDrawable的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
protected void onResume() {
super.onResume();
int color = SettingUtil.getInstance().getColor();
int drawable = Constant.ICONS_DRAWABLES[SettingUtil.getInstance().getCustomIconValue()];
if (getSupportActionBar() != null)
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(color));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(CircleView.shiftColorDown(color));
// 最近任务栏上色
ActivityManager.TaskDescription tDesc = new ActivityManager.TaskDescription(
getString(R.string.app_name),
BitmapFactory.decodeResource(getResources(), drawable),
color);
setTaskDescription(tDesc);
if (SettingUtil.getInstance().getNavBar()) {
getWindow().setNavigationBarColor(CircleView.shiftColorDown(color));
} else {
getWindow().setNavigationBarColor(Color.BLACK);
}
}
}
private void initList() {
View popupWindow_view = LayoutInflater.from(context).inflate(
R.layout.droppopmenu, null);
popupWindow_view.setFocusableInTouchMode(true);
// 设置popupWindow的布局
popupWindow = new PopupWindow(popupWindow_view,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT);
popupWindow.setTouchable(true);
popupWindow.setFocusable(true);
// 这个是为了点击“返回Back”也能使其消失,并且并不会影响你的背景
popupWindow.setBackgroundDrawable(new ColorDrawable(
android.R.color.transparent));
// 设置允许在外点击消失
popupWindow.setOutsideTouchable(true);
listView = (ListView) popupWindow_view
.findViewById(R.id.droppopmenu_listView);
popupWindow.update();
}
/**
* 长按弹出菜单
*
* @param offsetY
* @param actionMenu
* @return 菜单创建成功,返回true
*/
private void showActionMenu(int offsetY, ActionMenu actionMenu) {
mActionMenuPopupWindow = new PopupWindow(actionMenu, WindowManager.LayoutParams.WRAP_CONTENT,
mActionMenuHeight, true);
mActionMenuPopupWindow.setFocusable(true);
mActionMenuPopupWindow.setOutsideTouchable(false);
mActionMenuPopupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
mActionMenuPopupWindow.showAtLocation(this, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, offsetY);
mActionMenuPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
@Override
public void onDismiss() {
Selection.removeSelection(getEditableText());
// 如果设置了分散对齐,ActionMenu销毁后,强制刷新一次,防止出现文字背景未消失的情况
if (isTextJustify)
SelectableTextView.this.postInvalidate();
}
});
}
@Test
public void testErrorDefaultFade() {
ColorDrawable defaultDrawable = new ColorDrawable(Color.BLUE);
ColorDrawable errorDrawable = new ColorDrawable(Color.BLACK);
CrossbowImage.Builder builder = new CrossbowImage.Builder(RuntimeEnvironment.application, null, null);
builder.placeholder(defaultDrawable);
builder.error(errorDrawable);
builder.fade(200);
CrossbowImage crossbowImage = builder.into(imageView).load();
crossbowImage.setError(null);
TransitionDrawable drawable = (TransitionDrawable) imageView.getDrawable();
assertTrue(drawable.getNumberOfLayers() == 2);
}
/**
* Initialise DaVinci, muse have a googleApiClient to retrieve Bitmaps from Smartphone
*
* @param context the application context
* @param size the number of entry on the cache
*/
private DaVinci(Context context, int size) {
Log.d(TAG, "====================================");
this.mSize = size;
this.mContext = context;
this.mImagesCache = new LruCache<>(mSize);
this.mDiskImageCache= new DiskLruImageCache(mContext, TAG, cacheSize, Bitmap.CompressFormat.PNG, 100);
this.mPlaceHolder = new ColorDrawable(Color.TRANSPARENT);
mApiClient = new GoogleApiClient.Builder(context)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mApiClient.connect();
//TODO disconnect when the application close
}
public static Dialog getDialog(Context context, String message, String title) {
View view = LayoutInflater.from(context).inflate(R.layout.custome_dialoge_title, null);
TextView titleTextView = view.findViewById(R.id.tvInfo);
titleTextView.setText(title);
TextView textView = view.findViewById(R.id.tvDialogeText);
textView.setText(message);
Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(view);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
return dialog;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
Window dialogWindow = getDialog().getWindow();
if (null != dialogWindow) {
WindowManager.LayoutParams attrs = dialogWindow.getAttributes();
attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
dialogWindow.setAttributes(attrs);
dialogWindow.requestFeature(Window.FEATURE_NO_TITLE);
}
super.onActivityCreated(savedInstanceState);
if (null != dialogWindow) {
dialogWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
dialogWindow.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
dialogWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
}
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
setBackground(new ColorDrawable(
ApiCompatibilityUtils.getColor(getResources(), R.color.default_primary_color)));
mUrlBar = (UrlBar) findViewById(R.id.url_bar);
mUrlBar.setHint("");
mUrlBar.setDelegate(this);
mUrlBar.setEnabled(false);
mUrlBar.setAllowFocus(false);
mTitleBar = (TextView) findViewById(R.id.title_bar);
mLocationBarFrameLayout = findViewById(R.id.location_bar_frame_layout);
mTitleUrlContainer = findViewById(R.id.title_url_container);
mTitleUrlContainer.setOnLongClickListener(this);
mSecurityButton = (TintedImageButton) findViewById(R.id.security_button);
mSecurityIconType = ConnectionSecurityLevel.NONE;
mCustomActionButton = (ImageButton) findViewById(R.id.action_button);
mCustomActionButton.setOnLongClickListener(this);
mCloseButton = (ImageButton) findViewById(R.id.close_button);
mCloseButton.setOnLongClickListener(this);
mAnimDelegate = new CustomTabToolbarAnimationDelegate(mSecurityButton, mTitleUrlContainer);
}
public RequestSendtoAdmin(Context context, int id, String number,String name, String request, Object dashBoardActivity) {
super(context);
// TODO Auto-generated constructor stub
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.dialog_send_request_admin);
getWindow().setBackgroundDrawable(new ColorDrawable(android.R.color.transparent));
setCancelable(false);
this.context = context;
roboto = Typeface.createFromAsset(context.getAssets(),"font/Roboto-Regular.ttf");
activity = (Activity) context;
this.requestSend= request;
this.groupName= name;
this.groupNumber= number;
this.gUID= id;
dashBoardActObjecct = dashBoardActivity;
shared = new SharedPreferanceData(context);
requestDilog = this;
comman = new Comman();
}
public BaseLibraryActivityViewModel(Context context, boolean fitSystemWindows) {
super(context);
mFitSystemWindows = fitSystemWindows;
mExpandedHeight = getDimensionPixelSize(R.dimen.miniplayer_height);
mAnimateSlideInOut = false;
mMiniplayerHeight = new ObservableInt(0);
mMiniplayerAlpha = new ObservableFloat(1.0f);
mNowPlayingToolbarAlpha = new ObservableFloat(0.0f);
int backgroundColor = getColor(R.color.background);
mNowPlayingBackground = new ColorDrawable(backgroundColor);
setPlaybackOngoing(false);
mMiniplayerHeight.addOnPropertyChangedCallback(new OnPropertyChangedCallback() {
@Override
public void onPropertyChanged(androidx.databinding.Observable sender, int propertyId) {
notifyPropertyChanged(BR.miniplayerShadowAlpha);
}
});
}
@Override
public void onBindViewHolder(EditServiceViewHolder holder, int position) {
GridLayoutManager.LayoutParams params = new GridLayoutManager.LayoutParams(mItemSize, mItemSize);
holder.itemView.setLayoutParams(params);
holder.mEditImageView.setImageResource(editBtnResId);
holder.mEditImageView.setVisibility(isEditStatus ? View.VISIBLE : View.INVISIBLE);
Services service = mData.get(position);
ZjbImageLoader.create(service.getIcon())
.setBitmapConfig(Bitmap.Config.ARGB_8888)
.setDisplayType(ZjbImageLoader.DISPLAY_DEFAULT)
.setDefaultDrawable(new ColorDrawable(0xffe0dedc))
.into(holder.mImageView);
holder.itemView.setOnClickListener(v -> {
if (null != mListener && isEditStatus) {
mListener.onItemClick(service, holder.getAdapterPosition());
}
});
}
/**
* 创建左滑菜单
*/
private SwipeMenuCreator newMenuCreator() {
return new SwipeMenuCreator() {
@Override
public void create(SwipeMenu menu) {
SwipeMenuItem deleteItem = new SwipeMenuItem(getContext());
deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9, 0x3F, 0x25)));
deleteItem.setWidth(DisplayUtil.dip2px(getContext(), 80f));
deleteItem.setTitle("删除");
deleteItem.setTitleSize(14);
deleteItem.setTitleColor(Color.WHITE);
menu.addMenuItem(deleteItem);
}
};
}
/**
* Called when the processing is complete and the final drawable should be
* set on the ImageView.
*
* @param imageView
* @param drawable
*/
private void setImageDrawable(ImageView imageView, Drawable drawable) {
if (mFadeInBitmap) {
// Transition drawable with a transparent drawable and the final drawable
final TransitionDrawable td =
new TransitionDrawable(new Drawable[] {
new ColorDrawable(android.R.color.transparent),
drawable
});
// Set background to loading bitmap
imageView.setBackgroundDrawable(
new BitmapDrawable(mResources, mLoadingBitmap));
imageView.setImageDrawable(td);
td.startTransition(FADE_IN_TIME);
} else {
imageView.setImageDrawable(drawable);
}
}
@Override
public void apply(View view) {
if (view instanceof ImageView) {
ImageView imageView = (ImageView) view;
if (RES_TYPE_NAME_DRAWABLE.equals(attrValueTypeName)) {
Drawable bg = AndroidSkin.getInstance().getSkinDrawable(
attrValueTypeName, attrValueRefName, attrValueRefId);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
imageView.setImageDrawable(bg);
} else {
imageView.setImageDrawable(bg);
}
}else if (RES_TYPE_NAME_COLOR.equals(attrValueTypeName)){
int color = AndroidSkin.getInstance().
getSkinColor(attrValueTypeName, attrValueRefName, attrValueRefId);
imageView.setImageDrawable(new ColorDrawable(color));
}
}else {
LogUtils.d(TAG,"ImageSrcAttr apply src not ImageView! ");
}
}
private Bitmap getBitmapFromDrawable(Drawable drawable) {
if (drawable == null) {
return null;
}
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
}
try {
Bitmap bitmap;
if (drawable instanceof ColorDrawable) {
bitmap = Bitmap.createBitmap(COLORDRAWABLE_DIMENSION, COLORDRAWABLE_DIMENSION, BITMAP_CONFIG);
} else {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), BITMAP_CONFIG);
}
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public void changeBgColor(){
//root
new ColorPanel(this,((ColorDrawable) findView(R.id.note_edit_editText).getBackground()).getColor()).setOnColorChoseCallback(new ColorPanel.OnColorChoseCallback() {
@Override
public void onColorChose(@ColorInt int color) {
AppPreferenceUtil.setEditBgColor(color);
loadEditBgColor();
}
});
}
public void show() {
View anchor = context.getWindow().getDecorView().getRootView();
setContentView(new DebugLayout(context, anchor));
getContentView().setLayoutParams(new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
setBackgroundDrawable(new ColorDrawable(context.getResources().getColor(android.R.color.transparent)));
setTouchable(false);
setFocusable(false);
setOutsideTouchable(false);
setAnimationStyle(0);
super.showAtLocation(anchor, Gravity.START | Gravity.TOP, 0, 0);
update(anchor.getWidth(), anchor.getHeight());
anchor.getViewTreeObserver().addOnPreDrawListener(listener);
}
public static ProgressDialog showLoadingDialog(Context context) {
ProgressDialog progressDialog = new ProgressDialog(context);
progressDialog.show();
if (progressDialog.getWindow() != null) {
progressDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
}
progressDialog.setContentView(R.layout.progress_dialog);
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(true);
progressDialog.setCanceledOnTouchOutside(false);
return progressDialog;
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getListView().setBackgroundColor(0xffffffff);
getListView().setDivider(new ColorDrawable(0xff7f7f7f));
getListView().setDividerHeight(1);
getListView().setOnItemClickListener(this);
final String name = getIntent().getExtras().getString("name");
setTitle(getString(R.string.car_api_title_series_name, name));
// 根据车系名称查询车型
Car api = ResHelper.forceCast(MobAPI.getAPI(Car.NAME));
api.querySeriesName(name, this);
}
private void setDividerColor(int color) {
boolean setDivider = false;
boolean setTextSize = false;
java.lang.reflect.Field[] pickerFields = android.widget.NumberPicker.class.getDeclaredFields();
for (java.lang.reflect.Field pf : pickerFields) {
try {
if (pf.getName().equals(DIVIDER)) {
pf.setAccessible(true);
ColorDrawable colorDrawable = new ColorDrawable(color);
pf.set(this, colorDrawable);
setDivider = true;
}
else if (pf.getName().equals(TEXT_SIZE)) {
// Not setting the text size (since we increased to a larger size) was causing the
// measurement of the view to be "off". When a scroll took place, the offsets
// were all out of sync as to how far to scroll to get to the next view. This was causing
// the picker to look like it was shaking violently everytime it reached a min/max value and you
// tried to scroll away.
pf.setAccessible(true);
pf.set(this, FONT_SP_SIZE);
setTextSize = true;
}
if (setDivider && setTextSize) {
break;
}
}
catch (Exception ex) {
// No - Op.
}
}
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
final int action = event.getAction();
final float y = event.getY();// 点击y坐标
final int oldChoose = choose;
final OnTouchingLetterChangedListener listener = onTouchingLetterChangedListener;
final int c = (int) (y / getHeight() * b.length);// 点击y坐标所占总高度的比例*b数组的长度就等于点击b中的个数.
switch (action) {
case MotionEvent.ACTION_UP:
setBackgroundDrawable(new ColorDrawable(0x00000000));
choose = -1;//
invalidate();
if (mTextDialog != null) {
mTextDialog.setVisibility(View.INVISIBLE);
}
break;
default:
// 设置右侧字母列表[A,B,C,D,E....]的背景颜色
setBackgroundResource(R.drawable.v2_sortlistview_sidebar_background);
if (oldChoose != c) {
if (c >= 0 && c < b.length) {
if (listener != null) {
listener.onTouchingLetterChanged(b[c]);
}
if (mTextDialog != null) {
mTextDialog.setText(b[c]);
mTextDialog.setVisibility(View.VISIBLE);
}
choose = c;
invalidate();
}
}
break;
}
return true;
}
public ChatMessagesAdapter(ChatMessagesFragment fragment, List<MessageInfo> messages,
List<MessageId> messageIds) {
mFragment = fragment;
StyledAttributesHelper ta = StyledAttributesHelper.obtainStyledAttributes(fragment.getContext(),
new int[] { R.attr.selectableItemBackground, R.attr.colorControlHighlight });
// mItemBackground = ta.getDrawable(R.attr.selectableItemBackground);
int color = ta.getColor(R.attr.colorControlHighlight, 0);
//color = ColorUtils.setAlphaComponent(color, Color.alpha(color) / 2);
mSelectedItemBackground = new ColorDrawable(color);
ta.recycle();
setMessages(messages, messageIds);
setHasStableIds(true);
}
private void clearAdapter() {
if (mAdapter == null) return;
mAdapter.clearItems();
if (mSearchResult.getVisibility() == View.VISIBLE) {
AnimationHelper.fade(mSearchResult).start();
}
AnimationHelper.setBackgroundColor(mRecyclerView,
((ColorDrawable) mRecyclerView.getBackground()).getColor(),
Color.TRANSPARENT)
.interpolator(new LinearOutSlowInInterpolator())
.start();
}
private Bitmap getBitmapFromDrawable(Drawable drawable) {
if (drawable == null) {
return null;
}
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
}
try {
Bitmap bitmap;
if (drawable instanceof ColorDrawable) {
bitmap = Bitmap.createBitmap(COLORDRAWABLE_DIMENSION, COLORDRAWABLE_DIMENSION, BITMAP_CONFIG);
} else {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), BITMAP_CONFIG);
}
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setBackgroundDrawable(new ColorDrawable((backgroundFromColor = getIntent().getIntExtra(WaveCompat.IntentKey.BACKGROUND_COLOR, 0xff8B7D6B))));
// WaveCompat.transitionInitial(this, ABTextUtil.dip2px(context, 80), backgroundFromColor, Color.GRAY);
}
private Bitmap getBitmapFromDrawable(Drawable drawable) {
if (drawable == null) {
return null;
}
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
}
try {
Bitmap bitmap;
if (drawable instanceof ColorDrawable) {
bitmap = Bitmap.createBitmap(COLORDRAWABLE_DIMENSION, COLORDRAWABLE_DIMENSION, BITMAP_CONFIG);
} else {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), BITMAP_CONFIG);
}
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
public int getColor(View view) {
Drawable bg = view.getBackground();
if(bg instanceof ColorDrawable){
return ((ColorDrawable) bg).getColor();
}
return 0;
}
@Override
public Integer get(FrameLayout layout) {
if (layout.getForeground() instanceof ColorDrawable) {
return ((ColorDrawable) layout.getForeground()).getColor();
} else {
return Color.TRANSPARENT;
}
}
@Override
public Drawable getDrawable(ImageHolder holder, RichTextConfig config, TextView textView) {
ColorDrawable drawable = new ColorDrawable(Color.DKGRAY);
int width = textView.getWidth();
drawable.setBounds(0, 0, width, width / 2);
HANDLER.obtainMessage(SET_BOUNDS, Pair.create(drawable, textView)).sendToTarget();
return drawable;
}
@Override
public void onClick(View v) {
WindowManager wm = getActivity().getWindowManager();
final int size = wm.getDefaultDisplay().getWidth() / 3 * 2;
if (v.getId() == btnAlbumSelected.getId()) {
if (folderPopupWindow == null) {
createPopupFolderList(size, size);
}
if (folderPopupWindow.isShowing()) {
folderPopupWindow.dismiss();
} else {
folderPopupWindow.show();
if (folderPopupWindow.getListView() != null) {
folderPopupWindow.getListView().setDivider(new ColorDrawable(ContextCompat.getColor(getActivity(), R.color.bottom_bg)));
}
int index = folderListAdapter.getSelectIndex();
index = index == 0 ? index : index - 1;
folderPopupWindow.getListView().setSelection(index);
folderPopupWindow.getListView().getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
folderPopupWindow.getListView().getViewTreeObserver().removeGlobalOnLayoutListener(this);
} else {
folderPopupWindow.getListView().getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
int h = folderPopupWindow.getListView().getMeasuredHeight();
if (h > size) {
folderPopupWindow.setHeight(size);
folderPopupWindow.show();
}
}
});
setBackgroundAlpha(0.6f);
}
}
}