`

自动调整TextView字体大小以适应文字长度&拖动一个角增大textView面积

阅读更多
效果是 当字数少的时候 字体最大,随着字数的增多字体逐渐减小。
import android.content.Context;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.TextView;

public class CustomTextView extends TextView {

	private static float DEFAULT_MIN_TEXT_SIZE = 10;
	private static float DEFAULT_MAX_TEXT_SIZE = 20;

	// Attributes
	private Paint testPaint;
	private float minTextSize, maxTextSize;

	public CustomTextView(Context context, AttributeSet attrs) {
		super(context, attrs);
		initialise();
	}

	private void initialise() {
		testPaint = new Paint();
		testPaint.set(this.getPaint());

		// max size defaults to the intially specified text size unless it is
		// too small
		maxTextSize = this.getTextSize();

		if (maxTextSize <= DEFAULT_MIN_TEXT_SIZE) {
			maxTextSize = DEFAULT_MAX_TEXT_SIZE;
		}

		minTextSize = DEFAULT_MIN_TEXT_SIZE;
	};

	/**
	 * Re size the font so the specified text fits in the text box * assuming
	 * the text box is the specified width.
	 */
	private void refitText(String text, int textWidth) {
		if (textWidth > 0) {
			int availableWidth = textWidth - this.getPaddingLeft()
					- this.getPaddingRight();
			float trySize = maxTextSize;
			testPaint.setTextSize(trySize);
			while ((trySize > minTextSize)
					&& (testPaint.measureText(text) > availableWidth)) {
				trySize -= 1;
				if (trySize <= minTextSize) {
					trySize = minTextSize;
					break;
				}
				testPaint.setTextSize(trySize);
			}
			this.setTextSize(trySize);
		}
	};

	@Override
	protected void onTextChanged(CharSequence text, int start, int before,
			int after) {
		super.onTextChanged(text, start, before, after);
		refitText(text.toString(), this.getWidth());
	}

	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		if (w != oldw) {
			refitText(this.getText().toString(), w);
		}
	}
}



拖动一个角增大textView面积
public class EditTextClass extends Activity implements OnTouchListener {

    private EditText txt;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        txt = (EditText) findViewById(YourEditTextId);
        txt.setOnTouchListener(this);
    }


    @Override
    public boolean onTouch(View v, MotionEvent event) {
       if(event.getX() >= txt.getWidth() - 5 && event.getX() <= txt.getWidth()
            event.getY() >= txt.getHeight() - 5 && event.getY() <= txt.getHeight()) {
           txt.setWidth(event.getX()); 
           txt.setHeight(event.getY());
       }
       return true;
    }
}


ImageView伸缩动画效果
http://edison-cool911.iteye.com/blog/870339
分享到:
评论
1 楼 安轩之 2011-09-20  
楼主,你写的是否有误???

相关推荐

Global site tag (gtag.js) - Google Analytics