下面列出了android.widget.TextView#getPaint ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void initView() {
initToolbar();
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
mPage_content = (LinearLayout) findViewById(R.id.page_content);
mLoadingPage = (LoadingPage) findViewById(R.id.loading_page);
details_title = (TextView) this.findViewById(R.id.details_title);
// 设置标题加粗
TextPaint tp = details_title.getPaint();
tp.setFakeBoldText(true);
details_name = (TextView) this.findViewById(R.id.details_name);
details_time = (TextView) this.findViewById(R.id.details_time);
mWebView = (WebView) this.findViewById(details_content);
showLoadingPage();
}
public Card(Context context) {
super(context);
LayoutParams lp = null;
background = new View(getContext());
lp = new LayoutParams(-1, -1);
lp.setMargins(10, 10, 0, 0);
background.setBackgroundColor(getResources().getColor(
R.color.normalCardBack));
addView(background, lp);
label = new TextView(getContext());
label.setTextSize(28);
label.setGravity(Gravity.CENTER);
TextPaint tp = label.getPaint();
tp.setFakeBoldText(true);
lp = new LayoutParams(-1, -1);
lp.setMargins(10, 10, 0, 0);
addView(label, lp);
setNum(0);
}
TextView getTextView() {
//设置TextView的样式
AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, 64);
TextView textView = new TextView(
mContext);
textView.setLayoutParams(lp);
textView.setGravity(Gravity.CENTER_VERTICAL);
//设置TextView的Padding值
textView.setPadding(16, -10, 0, 32);
//设置TextView的字体大小
textView.setTextSize(14);
//设置TextView的字体颜色
textView.setTextColor(Color.WHITE);
//设置字体加粗
TextPaint txt = textView.getPaint();
txt.setFakeBoldText(true);
return textView;
}
/**
* 设置箭头方向
*/
private void setArrowDirection(TextView tv_tab, boolean isUp) {
TextPaint textPaint = tv_tab.getPaint();
if (isUp) {
if (tab_text_style == 1) {
textPaint.setFakeBoldText(true);
}
tv_tab.setTextColor(btnTextSelect);
tv_tab.setCompoundDrawablesWithIntrinsicBounds(0, 0, tab_arrow_select, 0);
} else {
textPaint.setFakeBoldText(false);
tv_tab.setTextColor(btnTextUnSelect);
tv_tab.setCompoundDrawablesWithIntrinsicBounds(0, 0, tab_arrow_unselect, 0);
}
}
TextView getTextView() {
//设置TextView的样式
AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, 64);
TextView textView = new TextView(
mContext);
textView.setLayoutParams(lp);
textView.setGravity(Gravity.CENTER_VERTICAL);
//设置TextView的Padding值
textView.setPadding(16, -10, 0, 32);
//设置TextView的字体大小
textView.setTextSize(14);
//设置TextView的字体颜色
textView.setTextColor(Color.WHITE);
//设置字体加粗
TextPaint txt = textView.getPaint();
txt.setFakeBoldText(true);
return textView;
}
public PDFTextView(Context context) {
super(context);
setOrientation(VERTICAL);
setMinimumHeight(screenHeight / 3);
textView = new TextView(context);
LayoutParams lp = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.CENTER_HORIZONTAL;
addView(textView, lp);
setPadding(0, 40, 0, 40);
setBackgroundColor(context.getResources().getColor(R.color.text_reflow_bg_color));
mPaint = textView.getPaint();
mTextSize = mPaint.getTextSize();
mPaint.setTextSize(mTextSize * 1.2f);
// html:行间距要调小,会导致图文重排图片上移,段间距偏大,行间距也偏大,
// xhtml:默认不修改,文本行间距偏小,段间距偏大.
// text:所有文本不换行,显示不对.剩下与xhtml相同.如果不使用Html.from设置,有换行,但显示不了图片.
// textView.setLineSpacing(0, 0.8f);
textView.setPadding(30, 0, 30, 0);
textView.setTextColor(context.getResources().getColor(R.color.text_reflow_color));
//textView.setTextIsSelectable(true);
minImgHeight = textView.getPaint().measureText("我") + 5;
}
/**
* Computes and records the minimum width required to display any of the values without
* causing another layout pass when switching values.
*/
int computeMinWidthRequiredForValues() {
DualControlLayout layout = getView(0, null, null);
TextView container = (TextView) layout.getChildAt(1);
Paint textPaint = container.getPaint();
float longestLanguageWidth = 0;
for (int i = 0; i < getCount(); i++) {
float width = textPaint.measureText(getItem(i).toString());
longestLanguageWidth = Math.max(longestLanguageWidth, width);
}
mMinWidthRequiredForValues = (int) Math.ceil(longestLanguageWidth);
return mMinWidthRequiredForValues;
}
protected static int getWordWidth() {
Context context = getGDActivity();
String text = "W";
TextView textView = new TextView(context);
textView.setTextSize(ClickableMenuElement.TEXT_SIZE);
textView.setTypeface(Global.robotoCondensedTypeface);
Rect bounds = new Rect();
Paint textPaint = textView.getPaint();
textPaint.getTextBounds(text, 0, text.length(), bounds);
return bounds.width() + getDp(WORD_SPACE);
}
/**
* 判断TextView的内容宽度是否超出其可用宽度
*
* @param tv
* @return
*/
public static boolean isOverFlowed(TextView tv, int maxWidth) {
int availableWidth = maxWidth - tv.getPaddingLeft() - tv.getPaddingRight();
Paint textViewPaint = tv.getPaint();
float textWidth = textViewPaint.measureText(tv.getText().toString());
if (textWidth > availableWidth) {
return true;
} else {
return false;
}
}
/**
* 计算TextView 的宽度
* @param textView
* @param text
* @return
*/
public static float getTextViewLength(TextView textView,String text){
TextPaint paint = textView.getPaint();
// 得到使用该paint写上text的时候,像素为多少
float textLength = paint.measureText(text);
return textLength;
}
public static int measureTextView(TextView tv) {
if (tv == null) {
return -1;
}
Paint p = tv.getPaint();
return (int) p.measureText(tv.getText().toString());
}
public static void handleNickName(ThreadRowInfo row, int fgColor,
TextView nickNameTV, Context context) {
initStaticStrings(context);
String nickName = row.getAuthor();
// int now = 0;
if ("-1".equals(row.getYz()))// nuked
{
fgColor = nickNameTV.getResources().getColor(R.color.title_red);
nickName += "(VIP)";
} else if (!StringUtils.isEmpty(row.getMuteTime())
&& !"0".equals(row.getMuteTime()) || row.isMuted()) {
fgColor = nickNameTV.getResources().getColor(R.color.title_orange);
nickName += "(" + legend + ")";
}
if (row.get_isInBlackList()) {
fgColor = nickNameTV.getResources().getColor(R.color.title_orange);
nickName += "(" + blacklistban + ")";
}
if (row.getISANONYMOUS()) {
fgColor = nickNameTV.getResources().getColor(R.color.title_red);
nickName += "(匿名)";
}
nickNameTV.setText(nickName);
TextPaint tp = nickNameTV.getPaint();
tp.setFakeBoldText(true);// bold for Chinese character
nickNameTV.setTextColor(fgColor);
}
private void adjustWidth (TextView view, RelativeLayout.LayoutParams params, String text)
{
Paint tpaint;
tpaint = view.getPaint ();
params.width = (int) Math.max (params.width, tpaint.measureText (text));
}
@Nullable
private static PrecomputedTextCompat precomputedText(@Nullable TextView textView, @NonNull Spanned spanned) {
if (textView == null) {
return null;
}
final PrecomputedTextCompat.Params params;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
// use native parameters on P
params = new PrecomputedTextCompat.Params(textView.getTextMetricsParams());
} else {
final PrecomputedTextCompat.Params.Builder builder =
new PrecomputedTextCompat.Params.Builder(textView.getPaint());
// please note that text-direction initialization is omitted
// by default it will be determined by the first locale-specific character
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// another miss on API surface, this can easily be done by the compat class itself
builder
.setBreakStrategy(textView.getBreakStrategy())
.setHyphenationFrequency(textView.getHyphenationFrequency());
}
params = builder.build();
}
return PrecomputedTextCompat.create(spanned, params);
}
/**
* Get desired popup window width by calculating the maximum text length from Autofill data.
* @param data Autofill suggestion data.
* @return The popup window width in DIP.
*/
private float getDesiredWidth(ArrayList<AutofillSuggestion> data) {
if (mLabelViewPaint == null || mSublabelViewPaint == null) {
LayoutInflater inflater =
(LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.autofill_text, null);
TextView labelView = (TextView) layout.findViewById(R.id.autofill_label);
mLabelViewPaint = labelView.getPaint();
TextView sublabelView = (TextView) layout.findViewById(R.id.autofill_sublabel);
mSublabelViewPaint = sublabelView.getPaint();
}
float maxTextWidth = 0;
Rect bounds = new Rect();
for (int i = 0; i < data.size(); ++i) {
bounds.setEmpty();
String label = data.get(i).mLabel;
if (!TextUtils.isEmpty(label)) {
mLabelViewPaint.getTextBounds(label, 0, label.length(), bounds);
}
float labelWidth = bounds.width();
bounds.setEmpty();
String sublabel = data.get(i).mSublabel;
if (!TextUtils.isEmpty(sublabel)) {
mSublabelViewPaint.getTextBounds(sublabel, 0, sublabel.length(), bounds);
}
float localMax = Math.max(labelWidth, bounds.width());
maxTextWidth = Math.max(maxTextWidth, localMax);
}
// Scale it down to make it unscaled by screen density.
maxTextWidth = maxTextWidth / mContext.getResources().getDisplayMetrics().density;
// Adding padding.
return maxTextWidth + TEXT_PADDING_DP;
}
private int getTextWidth(TextView textView) {
if (textView == null) {
return 0;
}
Rect bounds = new Rect();
String text = textView.getText().toString();
Paint paint = textView.getPaint();
paint.getTextBounds(text, 0, text.length(), bounds);
int width = bounds.left + bounds.width();
return width;
}
public static void justify(final TextView textView) {
// 标记是否已经进行过处理,因为 post 回调会在处理后继续触发
final AtomicBoolean isJustify = new AtomicBoolean(false);
// 处理前原始字符串
final String textString = textView.getText().toString();
// 用于测量文字宽度,计算分散对齐后的空格宽度
final TextPaint textPaint = textView.getPaint();
CharSequence textViewText = textView.getText();
// 分散对齐后的文字
final Spannable builder = textViewText instanceof Spannable ?
(Spannable) textViewText :
new SpannableString(textString);
// 在 TextView 完成测量绘制之后执行
textView.post(new Runnable() {
@Override
public void run() {
// 判断是否已经处理过
if (!isJustify.get()) {
// 获取原始布局总行数
final int lineCount = textView.getLineCount();
// 获取 textView 的宽度
final int textViewWidth = textView.getWidth();
for (int i = 0; i < lineCount; i++) {
// 获取行首字符位置和行尾字符位置来截取每行的文字
int lineStart = textView.getLayout().getLineStart(i);
int lineEnd = textView.getLayout().getLineEnd(i);
String lineString = textString.substring(lineStart, lineEnd);
// 最后一行不做处理
if (i == lineCount - 1) {
break;
}
// 行首行尾去掉空格以保证处理后的对齐效果
String trimSpaceText = lineString.trim();
String removeSpaceText = lineString.replaceAll(" ", "");
float removeSpaceWidth = textPaint.measureText(removeSpaceText);
float spaceCount = trimSpaceText.length() - removeSpaceText.length();
// 两端对齐时每个空格的重新计算的宽度
float eachSpaceWidth = (textViewWidth - removeSpaceWidth) / spaceCount;
// 两端空格需要单独处理
Set<Integer> endsSpace = spacePositionInEnds(lineString);
for (int j = 0; j < lineString.length(); j++) {
char c = lineString.charAt(j);
// 使用透明的 drawable 来填充空格部分
Drawable drawable = new ColorDrawable(0x00ffffff);
if (c == ' ') {
if (endsSpace.contains(j)) {
// 如果是两端的空格,则宽度置为 0
drawable.setBounds(0, 0, 0, 0);
} else {
drawable.setBounds(0, 0, (int) eachSpaceWidth, 0);
}
ImageSpan span = new ImageSpan(drawable);
builder.setSpan(span, lineStart + j, lineStart + j + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}
textView.setText(builder);
// 标记处理完毕
isJustify.set(true);
}
}
});
}
private int getTextWidth(TextView textView) {
Rect bounds = new Rect();
Paint textPaint = textView.getPaint();
textPaint.getTextBounds(textView.getText().toString(), 0, textView.getText().length(), bounds);
return bounds.width();
}
/**
* Create a TextDrawable. This uses the given TextView to initialize paint and has initial text
* that will be drawn. Initial text can also be useful for reserving space that may otherwise
* not be available when setting compound drawables.
*
* @param tv The TextView / EditText using to initialize this drawable
* @param initialText Optional initial text to display
* @param bindToViewsText Should this drawable mirror the text in the TextView
* @param bindToViewsPaint Should this drawable mirror changes to Paint in the TextView, like textColor, typeface, alpha etc.
* Note, this will override any changes made using setColorFilter or setAlpha.
*/
public TextDrawable(TextView tv, String initialText, boolean bindToViewsText, boolean bindToViewsPaint) {
this(tv.getPaint(), initialText);
ref = new WeakReference<>(tv);
if (bindToViewsText || bindToViewsPaint) {
if (bindToViewsText) {
tv.addTextChangedListener(this);
}
mBindToViewPaint = bindToViewsPaint;
}
}
/**
* z.chu
* @param tv
* @return textview contentwidth
*/
public float getTextViewContentWidth(TextView tv) {
TextPaint textPaint = tv.getPaint();
return textPaint.measureText(tv.getText() + "");
}