Java Code Examples for android.widget.TextView#getBackground()

The following examples show how to use android.widget.TextView#getBackground() . These examples are extracted from open source projects. 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
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        convertView = View.inflate(context, R.layout.item_choice_book_category, null);
    }
    TextView tvText = convertView.findViewById(R.id.tv_text);
    tvText.setText(getItem(position).getKindName());
    GradientDrawable drawable = (GradientDrawable) tvText.getBackground();
    if (lastPosition == position) {
        int selectedColor = ContextCompat.getColor(context, R.color.colorAccent);
        tvText.setTextColor(selectedColor);
        drawable.setStroke(DensityUtil.dp2px(context, 2), selectedColor);
    } else {
        int normalColor = ContextCompat.getColor(context, R.color.colorBarText);
        tvText.setTextColor(normalColor);
        drawable.setStroke(DensityUtil.dp2px(context, 2), normalColor);
    }
    return convertView;
}
 
Example 2
Source Project: animation-samples   File: TextResize.java    License: Apache License 2.0 5 votes vote down vote up
private static Bitmap captureTextBitmap(TextView textView) {
    Drawable background = textView.getBackground();
    textView.setBackground(null);
    int width = textView.getWidth() - textView.getPaddingLeft() - textView.getPaddingRight();
    int height = textView.getHeight() - textView.getPaddingTop() - textView.getPaddingBottom();
    if (width == 0 || height == 0) {
        return null;
    }
    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    canvas.translate(-textView.getPaddingLeft(), -textView.getPaddingTop());
    textView.draw(canvas);
    textView.setBackground(background);
    return bitmap;
}
 
Example 3
Source Project: a   File: FindFlowAdapter.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
    public View getView(com.kunfei.bookshelf.widget.flowlayout.FlowLayout parent, int position, MyFindKindGroupBean findKindGroupBean) {
        TextView tv = (TextView) LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_flow_find_item,
                parent, false);

        tv.setTag(findKindGroupBean.getGroupTag());
        tv.setText(findKindGroupBean.getGroupName());

        Random myRandom = new Random();
        int ranColor = 0xff000000 | myRandom.nextInt(0x00ffffff);
        //tv.setBackgroundColor(ranColor);


        GradientDrawable bgShape = (GradientDrawable)tv.getBackground();
        bgShape.setStroke(1, ranColor);

/*
         int roundRadius = 15; // 8px not dp

        int fillColor = Color.parseColor("#DFDFE0");
         bgShape.setColor(fillColor);
         bgShape.setCornerRadius(roundRadius);

*/
        tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(null != onItemClickListener){
                    onItemClickListener.itemClick(v,findKindGroupBean);
                }
            }
        });
        return tv;
    }
 
Example 4
Source Project: AssistantBySDK   File: RspMsgItemView.java    License: Apache License 2.0 5 votes vote down vote up
protected void init(Context mContext) {
    LayoutInflater iflater = LayoutInflater.from(mContext);
    iflater.inflate(R.layout.common_bubble_dialog_left, this);
    mTextView = (TextView) findViewById(R.id.common_bubble_left_text);
    mTextView.setOnTouchListener(this);
    mListDrawable = (LevelListDrawable) mTextView.getBackground();
}
 
Example 5
Source Project: atlas   File: TextResize.java    License: Apache License 2.0 5 votes vote down vote up
private static Bitmap captureTextBitmap(TextView textView) {
    Drawable background = textView.getBackground();
    textView.setBackground(null);
    int width = textView.getWidth() - textView.getPaddingLeft() - textView.getPaddingRight();
    int height = textView.getHeight() - textView.getPaddingTop() - textView.getPaddingBottom();
    if (width == 0 || height == 0) {
        return null;
    }
    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    canvas.translate(-textView.getPaddingLeft(), -textView.getPaddingTop());
    textView.draw(canvas);
    textView.setBackground(background);
    return bitmap;
}
 
Example 6
Source Project: android-instant-apps   File: TextResize.java    License: Apache License 2.0 5 votes vote down vote up
private static Bitmap captureTextBitmap(TextView textView) {
    Drawable background = textView.getBackground();
    textView.setBackground(null);
    int width = textView.getWidth() - textView.getPaddingLeft() - textView.getPaddingRight();
    int height = textView.getHeight() - textView.getPaddingTop() - textView.getPaddingBottom();
    if (width == 0 || height == 0) {
        return null;
    }
    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    canvas.translate(-textView.getPaddingLeft(), -textView.getPaddingTop());
    textView.draw(canvas);
    textView.setBackground(background);
    return bitmap;
}
 
Example 7
Source Project: android-login   File: TextSizeTransition.java    License: MIT License 5 votes vote down vote up
private static Bitmap captureTextBitmap(TextView textView) {
  Drawable background = textView.getBackground();
  textView.setBackground(null);
  int width = textView.getWidth() - textView.getPaddingLeft() - textView.getPaddingRight();
  int height = textView.getHeight() - textView.getPaddingTop() - textView.getPaddingBottom();
  if (width == 0 || height == 0) {
    return null;
  }
  Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
  Canvas canvas = new Canvas(bitmap);
  canvas.translate(-textView.getPaddingLeft(), -textView.getPaddingTop());
  textView.draw(canvas);
  textView.setBackground(background);
  return bitmap;
}
 
Example 8
Source Project: EditTag   File: EditTag.java    License: MIT License 5 votes vote down vote up
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
    boolean isHandle = false;
    if (actionId == EditorInfo.IME_ACTION_DONE) {
        String tagContent = editText.getText().toString();
        if (TextUtils.isEmpty(tagContent)) {
            // do nothing, or you can tip "can'nt add empty tag"
        } else {
            if (tagAddCallBack == null || (tagAddCallBack != null
                    && tagAddCallBack.onTagAdd(tagContent))) {
                TextView tagTextView = createTag(flowLayout, tagContent);
                if (defaultTagBg == null) {
                    defaultTagBg = tagTextView.getBackground();
                }
                tagTextView.setOnClickListener(EditTag.this);
                flowLayout.addView(tagTextView, flowLayout.getChildCount() - 1);
                tagValueList.add(tagContent);
                // reset action status
                editText.getText().clear();
                editText.performClick();
                isDelAction = false;
                isHandle = true;
            }
        }
    }
    return isHandle;
}
 
Example 9
Source Project: EditTag   File: EditTag.java    License: MIT License 5 votes vote down vote up
public boolean addTag(String tagContent) {
    if (TextUtils.isEmpty(tagContent)) {
        // do nothing, or you can tip "can't add empty tag"
        return false;
    } else {
        if (tagAddCallBack == null || (tagAddCallBack != null
                && tagAddCallBack.onTagAdd(tagContent))) {
            TextView tagTextView = createTag(flowLayout, tagContent);
            if (defaultTagBg == null) {
                defaultTagBg = tagTextView.getBackground();
            }
            tagTextView.setOnClickListener(EditTag.this);
            if (isEditableStatus) {
                flowLayout.addView(tagTextView, flowLayout.getChildCount() - 1);
            } else {
                flowLayout.addView(tagTextView);
            }

            tagValueList.add(tagContent);
            // reset action status
            editText.getText().clear();
            editText.performClick();
            isDelAction = false;
            return true;
        }
    }
    return false;
}
 
Example 10
private void setViewColor(TextView view, int color) {
    if (color == ORIGIN_COLOR) {
        view.setTextColor(mOriginBarTitleColor);
        if (view.getBackground() != null) {
            view.getBackground().clearColorFilter();
        }
    } else {
        view.setTextColor(color);
        if (view.getBackground() != null) {
            view.getBackground().setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
        }
    }
}
 
Example 11
Source Project: android-art-res   File: MainActivity.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    TextView textView = (TextView) findViewById(R.id.test_size);
    Drawable drawable = textView.getBackground();
    Log.e(TAG, "bg:" + drawable + "w:" + drawable.getIntrinsicWidth()
            + " h:" + drawable.getIntrinsicHeight());
}
 
Example 12
private void processContactImage(Contact contact, TextView textView, TextView alphabeticTextView, CircleImageView contactImage) {
    try {
        String contactNumber = "";
        char firstLetter = 0;
        contactNumber = contact.getDisplayName().toUpperCase();
        firstLetter = contact.getDisplayName().toUpperCase().charAt(0);

        if (contact != null) {
            if (firstLetter != '+') {
                alphabeticTextView.setText(String.valueOf(firstLetter));
            } else if (contactNumber.length() >= 2) {
                alphabeticTextView.setText(String.valueOf(contactNumber.charAt(1)));
            }
            Character colorKey = AlphaNumberColorUtil.alphabetBackgroundColorMap.containsKey(firstLetter) ? firstLetter : null;
            GradientDrawable bgShape = (GradientDrawable) alphabeticTextView.getBackground();
            bgShape.setColor(ApplozicService.getContext(context).getResources().getColor(AlphaNumberColorUtil.alphabetBackgroundColorMap.get(colorKey)));
        }

        alphabeticTextView.setVisibility(View.GONE);
        contactImage.setVisibility(View.VISIBLE);
        if (contact != null) {
            if (contact.isDrawableResources()) {
                int drawableResourceId = ApplozicService.getContext(context).getResources().getIdentifier(contact.getrDrawableName(), "drawable", ApplozicService.getContext(context).getPackageName());
                contactImage.setImageResource(drawableResourceId);
            } else {
                contactImageLoader.loadImage(contact, contactImage, alphabeticTextView);
            }
        }
        textView.setVisibility(contact != null && contact.isOnline() ? View.VISIBLE : View.GONE);
    } catch (Exception e) {

    }
}
 
Example 13
/**
 * This method loads the image for a Contact into the ImageView. If the user does not have image url set, it will create an alphabeticText image.
 * This will automatically check if the image is set and handle the views visibility by itself.
 *
 * @param imageView CircularImageView which loads the image for the user.
 * @param textView  TextView which will display the alphabeticText image.
 * @param contact   The Contact object whose image is to be displayed.
 */
public void loadContactImage(CircleImageView imageView, TextView textView, Contact contact) {
    try {
        textView.setVisibility(View.VISIBLE);
        imageView.setVisibility(View.GONE);
        String contactNumber = "";
        char firstLetter = 0;
        contactNumber = contact.getDisplayName().toUpperCase();
        firstLetter = contact.getDisplayName().toUpperCase().charAt(0);

        if (firstLetter != '+') {
            textView.setText(String.valueOf(firstLetter));
        } else if (contactNumber.length() >= 2) {
            textView.setText(String.valueOf(contactNumber.charAt(1)));
        }

        Character colorKey = AlphaNumberColorUtil.alphabetBackgroundColorMap.containsKey(firstLetter) ? firstLetter : null;
        GradientDrawable bgShape = (GradientDrawable) textView.getBackground();
        bgShape.setColor(context.getResources().getColor(AlphaNumberColorUtil.alphabetBackgroundColorMap.get(colorKey)));

        if (contact.isDrawableResources()) {
            textView.setVisibility(View.GONE);
            imageView.setVisibility(View.VISIBLE);
            int drawableResourceId = context.getResources().getIdentifier(contact.getrDrawableName(), "drawable", context.getPackageName());
            imageView.setImageResource(drawableResourceId);
        } else if (contact.getImageURL() != null) {
            loadImage(imageView, textView, contact.getImageURL(), 0);
        } else {
            textView.setVisibility(View.VISIBLE);
            imageView.setVisibility(View.GONE);
        }
    } catch (Exception e) {

    }
}
 
Example 14
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    View listItemView = convertView;
    if (convertView == null) {
        listItemView = LayoutInflater.from(getContext()).inflate(R.layout.earthquake_list_item, parent, false);
    }

    // Find the earthquake at the given position in the list of earthquakes
    Earthquake currentEarthquake = getItem(position);

    // Find the TextView with view ID magnitude
    TextView magnitudeView = (TextView) listItemView.findViewById(R.id.magnitude);
    // Display the magnitude of the current earthquake in that TextView
    magnitudeView.setText(formatMagnitude(currentEarthquake.getMagnitude()));
    // Set the proper background color on the magnitude circle.
    // Fetch the background from the TextView, which is a GradientDrawable.
    GradientDrawable magnitudeCircle = (GradientDrawable) magnitudeView.getBackground();

    // Get the appropriate background color based on the current earthquake magnitude
    int magnitudeColor = getMagnitudeColor(currentEarthquake.getMagnitude());

    // Set the color on the magnitude circle
    magnitudeCircle.setColor(magnitudeColor);

    // Find the TextView with view ID location
    TextView primaryLocationView = (TextView) listItemView.findViewById(R.id.primary_location);
    TextView offsetLocationView = (TextView) listItemView.findViewById(R.id.offset_location);

    String location = currentEarthquake.getLocation();
    String primaryLocation;
    String locationOffset;
    if (location.contains(LOCATION_SEPARATOR)) {
        String[] parts = location.split(LOCATION_SEPARATOR);
        locationOffset = parts[0] + LOCATION_SEPARATOR;
        primaryLocation = parts[1];
    } else {
        locationOffset = getContext().getString(R.string.near_the);
        primaryLocation = location;
    }

    primaryLocationView.setText(primaryLocation);
    offsetLocationView.setText(locationOffset);

    // Create a new Date object from the time in milliseconds of the earthquake
    Date dateObject = new Date(currentEarthquake.getTimeInMilliseconds());

    // Find the TextView with view ID date
    TextView dateView = (TextView) listItemView.findViewById(R.id.date);
    // Format the date string (i.e. "Mar 3, 1984")
    String formattedDate = formatDate(dateObject);
    // Display the date of the current earthquake in that TextView
    dateView.setText(formattedDate);

    // Find the TextView with view ID time
    TextView timeView = (TextView) listItemView.findViewById(R.id.time);
    // Format the time string (i.e. "4:30PM")
    String formattedTime = formatTime(dateObject);
    // Display the time of the current earthquake in that TextView
    timeView.setText(formattedTime);

    // Return the list item view that is now showing the appropriate dat
    return listItemView;
}
 
Example 15
protected void bindCategory(@NonNull Context context, @NonNull TextView noteCategory, boolean showCategory, @NonNull String category, int mainColor) {
    final boolean isDarkThemeActive = NotesApplication.isDarkThemeActive(context);
    noteCategory.setVisibility(showCategory && !category.isEmpty() ? View.VISIBLE : View.GONE);
    noteCategory.setText(category);

    @ColorInt int categoryForeground;
    @ColorInt int categoryBackground;

    if (isDarkThemeActive) {
        if (isColorDark(mainColor)) {
            if (contrastRatioIsSufficient(mainColor, Color.BLACK)) {
                categoryBackground = mainColor;
                categoryForeground = Color.WHITE;
            } else {
                categoryBackground = Color.WHITE;
                categoryForeground = mainColor;
            }
        } else {
            categoryBackground = mainColor;
            categoryForeground = Color.BLACK;
        }
    } else {
        categoryForeground = Color.BLACK;
        if (isColorDark(mainColor) || contrastRatioIsSufficient(mainColor, Color.WHITE)) {
            categoryBackground = mainColor;
        } else {
            categoryBackground = Color.BLACK;
        }
    }

    noteCategory.setTextColor(categoryForeground);
    if (noteCategory instanceof Chip) {
        ((Chip) noteCategory).setChipStrokeColor(ColorStateList.valueOf(categoryBackground));
        ((Chip) noteCategory).setChipBackgroundColor(ColorStateList.valueOf(isDarkThemeActive ? categoryBackground : Color.TRANSPARENT));
    } else {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            DrawableCompat.setTint(noteCategory.getBackground(), categoryBackground);
        } else {
            final GradientDrawable drawable = (GradientDrawable) noteCategory.getBackground();
            drawable.setStroke(1, categoryBackground);
            drawable.setColor(isDarkThemeActive ? categoryBackground : Color.TRANSPARENT);
        }
    }
}
 
Example 16
Source Project: Dashchan   File: ClickableToast.java    License: Apache License 2.0 4 votes vote down vote up
private ClickableToast(Holder holder) {
	this.holder = holder;
	Context context = holder.context;
	float density = ResourceUtils.obtainDensity(context);
	int innerPadding = (int) (8f * density);
	LayoutInflater inflater = LayoutInflater.from(context);
	View toast1 = inflater.inflate(LAYOUT_ID, null);
	View toast2 = inflater.inflate(LAYOUT_ID, null);
	TextView message1 = toast1.findViewById(android.R.id.message);
	TextView message2 = toast2.findViewById(android.R.id.message);
	View backgroundSource = null;
	Drawable backgroundDrawable = toast1.getBackground();
	if (backgroundDrawable == null) {
		backgroundDrawable = message1.getBackground();
		if (backgroundDrawable == null) {
			View messageParent = (View) message1.getParent();
			if (messageParent != null) {
				backgroundDrawable = messageParent.getBackground();
				backgroundSource = messageParent;
			}
		} else {
			backgroundSource = message1;
		}
	} else {
		backgroundSource = toast1;
	}

	StringBuilder builder = new StringBuilder();
	for (int i = 0; i < 100; i++) builder.append('W'); // Make long text
	message1.setText(builder); // Avoid minimum widths
	int measureSize = (int) (context.getResources().getConfiguration().screenWidthDp * density + 0.5f);
	toast1.measure(View.MeasureSpec.makeMeasureSpec(measureSize, View.MeasureSpec.AT_MOST),
			View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
	toast1.layout(0, 0, toast1.getMeasuredWidth(), toast1.getMeasuredHeight());
	Rect backgroundSourceTotalPadding = getViewTotalPadding(toast1, backgroundSource);
	Rect messageTotalPadding = getViewTotalPadding(toast1, message1);
	messageTotalPadding.left -= backgroundSourceTotalPadding.left;
	messageTotalPadding.top -= backgroundSourceTotalPadding.top;
	messageTotalPadding.right -= backgroundSourceTotalPadding.right;
	messageTotalPadding.bottom -= backgroundSourceTotalPadding.bottom;
	int horizontalPadding = Math.max(messageTotalPadding.left, messageTotalPadding.right) +
			Math.max(message1.getPaddingLeft(), message1.getPaddingRight());
	int verticalPadding = Math.max(messageTotalPadding.top, messageTotalPadding.bottom) +
			Math.max(message1.getPaddingTop(), message1.getPaddingBottom());

	ViewUtils.removeFromParent(message1);
	ViewUtils.removeFromParent(message2);
	LinearLayout linearLayout = new LinearLayout(context);
	linearLayout.setOrientation(LinearLayout.HORIZONTAL);
	linearLayout.setDividerDrawable(new ToastDividerDrawable(0xccffffff, (int) (density + 0.5f)));
	linearLayout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
	linearLayout.setDividerPadding((int) (4f * density));
	linearLayout.setTag(this);
	linearLayout.addView(message1, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
	linearLayout.addView(message2, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
	((LinearLayout.LayoutParams) message1.getLayoutParams()).weight = 1f;
	linearLayout.setPadding(horizontalPadding, verticalPadding, horizontalPadding, verticalPadding);

	partialClickDrawable = new PartialClickDrawable(backgroundDrawable);
	message1.setBackground(null);
	message2.setBackground(null);
	linearLayout.setBackground(partialClickDrawable);
	linearLayout.setOnTouchListener(partialClickDrawable);
	message1.setPadding(0, 0, 0, 0);
	message2.setPadding(innerPadding, 0, 0, 0);
	message1.setSingleLine(true);
	message2.setSingleLine(true);
	message1.setEllipsize(TextUtils.TruncateAt.END);
	message2.setEllipsize(TextUtils.TruncateAt.END);
	container = linearLayout;
	message = message1;
	button = message2;

	windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
}
 
Example 17
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.user_profile_fragment_layout, container, false);
    name_cardView = (CardView) view.findViewById(R.id.applzoic_name_cardView);
    email_cardView = (CardView) view.findViewById(R.id.applzoic_email_cardview);
    status_cardView = (CardView) view.findViewById(R.id.applzoic_last_sean_status_cardView);
    phone_cardView = (CardView) view.findViewById(R.id.applozic_user_phone_cardview);
    name = (TextView) view.findViewById(R.id.userName);
    status = (TextView) view.findViewById(R.id.applozic_user_status);
    email = (TextView) view.findViewById(R.id.email);
    phone = (TextView) view.findViewById(R.id.phone);
    contactImage = (CircleImageView) view.findViewById(R.id.contactImage);
    alphabeticTextView = (TextView) view.findViewById(R.id.alphabeticImage);

    Bundle bundle = getArguments();
    if (bundle != null) {
        contact = (Contact) bundle.getSerializable(ConversationUIService.CONTACT);
        contact = baseContactService.getContactById(contact.getContactIds());

        ((CustomToolbarListener)getActivity()).setToolbarTitle(contact.getDisplayName());

        name.setText(contact.getDisplayName());
        char firstLetter = contact.getDisplayName().toUpperCase().charAt(0);
        String contactNumber = contact.getDisplayName().toUpperCase();
        if (firstLetter != '+') {
            alphabeticTextView.setText(String.valueOf(firstLetter));
        } else if (contactNumber.length() >= 2) {
            alphabeticTextView.setText(String.valueOf(contactNumber.charAt(1)));
        }
        Character colorKey = AlphaNumberColorUtil.alphabetBackgroundColorMap.containsKey(firstLetter) ? firstLetter : null;
        GradientDrawable bgShape = (GradientDrawable) alphabeticTextView.getBackground();
        bgShape.setColor(getActivity().getResources().getColor(AlphaNumberColorUtil.alphabetBackgroundColorMap.get(colorKey)));
        if (contact.isDrawableResources()) {
            int drawableResourceId = getResources().getIdentifier(contact.getrDrawableName(), "drawable", getActivity().getPackageName());
            contactImage.setImageResource(drawableResourceId);
        } else {
            contactImageLoader.loadImage(contact, contactImage, alphabeticTextView);
        }


        name.setText(contact.getDisplayName());

        if (!TextUtils.isEmpty(contact.getEmailId())) {
            email_cardView.setVisibility(View.VISIBLE);
            email.setText(contact.getEmailId());
        }
        if (!TextUtils.isEmpty(contact.getStatus())) {
            status_cardView.setVisibility(View.VISIBLE);
            status.setText(contact.getStatus());
        }
        if (!TextUtils.isEmpty(contact.getContactNumber())) {
            phone_cardView.setVisibility(View.VISIBLE);
            phone.setText(contact.getContactNumber());
        } else {
            phone_cardView.setVisibility(View.GONE);
        }

    }

    return view;
}