您的位置:首页 > 移动开发 > Android开发

android 环绕TextView效果

2015-10-12 20:00 447 查看
效果图:



共有三个TextView组成,上面两个,下面一个TextView。

实现代码:

public class SurroundTextView {
//    private TextView leftTextView;//左边的文字,被环绕的文字
private TextView rightTextView;//右边的文字
private TextView bottomTextView;//下边的文字

private int count =0;//总共可以放多少个字
private float textTotalWidth = 0.0f;//textview全部字符的宽度
private float textWidth = 0.0f;//textview一个字的宽度
private Paint paint = new Paint();
private String textString;//需要显示的文字
private float moreWidth = 0;//多于加的宽度
private int height;

/**
* @param moreWidth 左边留出来的宽度
* @param rightText 右边文字
* @param bottomText 下边文字
* @param text 需要显示的文本
*/
public SurroundTextView(float moreWidth,int height, TextView rightText, TextView bottomText, String text) {
this.moreWidth = moreWidth;
this.rightTextView = rightText;
this.bottomTextView = bottomText;
this.textString = text;
this.height = height;
}

/**
* 绘制文本
* @param screenWidth 屏幕宽度
*/
public void drawImageViewDone(int screenWidth) {
//获取一个字的宽度
float textWidth = rightTextView.getTextSize();
paint.setTextSize(textWidth);

//        float width = leftTextView.getTextSize()*leftTextView.getText().toString().length() + moreWidth;
//        int height = leftTextView.getLineHeight();
// 一行字体的高度
int lineHeight = rightTextView.getLineHeight();
// 可以放多少行
int lineCount = (int) Math.ceil((double) height / (double) lineHeight);
// 一行的宽度
float rowWidth = screenWidth - moreWidth - rightTextView.getPaddingLeft() - rightTextView.getPaddingRight();
// 一行可以放多少个字
int columnCount = (int) (rowWidth / textWidth);

// 总共字体数等于 行数*每行个数
count = lineCount * columnCount;
// 一个TextView中所有字符串的宽度和(字体数*每个字的宽度)
textTotalWidth = (float) ((float) count * textWidth);
if (textWidth*textString.length() <=screenWidth){
System.out.println("这点东西不够换行啊----》"+textString);
rightTextView.setText(textString);
bottomTextView.setVisibility(View.GONE);
return;
}
measureText();
rightTextView.setText(textString.substring(0, count));

// 检查行数是否大于设定的行数,如果大于的话,就每次减少一个字符,重新计算行数与设定的一致
while (rightTextView.getLineCount() > lineCount) {
count -= 1;
rightTextView.setText(textString.substring(0, count));
}
bottomTextView.setPadding(0, lineCount * lineHeight - height, 0, 0);
System.out.println("下面显示的东西---》"+textString.substring(count));
bottomTextView.setText(textString.substring(count));
}
private void measureText(){
String string = textString.substring(0,count);
float size = paint.measureText(string);
int remainCount = (int)((textTotalWidth-size)/textWidth);
if (remainCount>0){
count+=remainCount;
measureText();
}
}
}


原理: 首先获取屏幕宽度,减去左边的宽度,绘制一个字检测一次是否到屏幕最大宽度。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: