用法:
public void setTextMy(String text,float textsize,int width)只需要設(shè)置text引润,字體大小和TextView顯示的寬度
源碼:
import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;
public class MyTextView extends TextView {
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public MyTextView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
/**setText
* @param text 顯示的字符串
* @param textsize 字體大小
* @param width TextView的寬度
*/
public void setTextMy(String text,float textsize,int width){
setSingleLine();//默認(rèn)單行
//sp2px(getContext(), textsize) 單個中文的寬度埂材,sp轉(zhuǎn)換成px適應(yīng)不同手機(jī)
int textWidth = sp2px(getContext(), textsize)*(getChineseNums(text)+(getNoChineseNums(text)+1)/2);
if (textWidth>width) {
int n = width/BaseUtils.sp2px(getContext(), textsize);
if(n-1<text.length()){
setText(text.substring(0, n-1)+"...");
}else{
setText(text);
}
}else{
setText(text);
}
}
/**字符串中嘿棘,中文的字?jǐn)?shù)
* @param str
* @return
*/
private int getChineseNums(String str) {
int byteLength = str.getBytes().length;
int strLength = str.length();
return (byteLength - strLength) / 2;
}
/**字符串中,非中文的字?jǐn)?shù)
* @param str
* @return
*/
private int getNoChineseNums(String str) {
int byteLength = str.getBytes().length;
int strLength = str.length();
return strLength - (byteLength - strLength) / 2;
}
/**
* 將sp值轉(zhuǎn)換為px值挨稿,保證文字大小不變
*
* @param spValue
* @param fontScale
* (DisplayMetrics類中屬性scaledDensity)
* @return
*/
public static int sp2px(Context context, float spValue) {
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (spValue * fontScale + 0.5f);
}
}