티스토리 뷰

(android.text.Layout 에 대한 참고 페이지 : http://sudarnimalan.blogspot.kr/2012/06/android-understating-text-drawing.html )

우선 항상 아래롤 스크롤되는 TextView 를 만들기 위해 다음과 같은 방법으로 스크롤을 가능하게 만들어줘야 한다.


::스크롤 가능한 TextView 만들기

mTextView.setMovementMethod(new ScrollingMovementMethod());


두 번째로 다음과 같은 메소드를 사용하여 항상 아래로 스크롤되는 텍스트 뷰를 적용할 수 있다.


:: 항상 아래로 스크롤되는 TextView 메소드.  (TextView 를 상속받는 EditText 에도 적용 가능하다.)

private void scrollBottom(TextView textView) {
	int lineTop =  textView.getLayout().getLineTop(textView.getLineCount()) ;
	int scrollY = lineTop - textView.getHeight();
	if (scrollY > 0) {
		textView.scrollTo(0, scrollY);
	} else {
		textView.scrollTo(0, 0);
	}
}


위 두 코드를 이용하여 아래와 같이 나름 재미있는(?) 예제를 만들어 보았다. 이 예제를 보면 이해가 쉬울 것이다. 


예제의 스크린샷 >

:: 응용 예제 코드 

import java.util.Random;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.text.method.ScrollingMovementMethod;
import android.view.ViewGroup.LayoutParams;
import android.widget.TextView;

public class MainActivity extends Activity {
	
	private TextView mTextView = null;
	private String[] mHello = {"하세요.", "?", "하십니까?.", "합쇼", "못한다."};
	private Random mRand = new Random(System.currentTimeMillis());
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTheme(android.R.style.Theme_Black_NoTitleBar_Fullscreen);
		mTextView = new TextView(getApplicationContext());
		mTextView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		setContentView(mTextView);
		mTextView.setMovementMethod(new ScrollingMovementMethod());
		mTextView.setTextSize(20);
		
		/**
		 * 100ms 마다 한 줄씩 랜덤한 컬러와 글자를 TextView 에 추가한다.
		 */
		mTextView.postDelayed(new Runnable() {
			@Override
			public void run() {
				String randomColor = toHexaColor(Color.rgb(mRand.nextInt(120 + 135), mRand.nextInt(120 + 135), mRand.nextInt(120 + 135)));
				Spanned htmlText = Html.fromHtml("<font  color=\"" + randomColor + "\">" + 
													  "안녕" + mHello[mRand.nextInt(mHello.length)] + 
													  "</font><br/>");
				mTextView.append(htmlText);
				scrollBottom(mTextView);
				mTextView.postDelayed(this, 100);
			}
		}, 100);
	}	
	
	/**
	 * 컬러 integer 값을 16진수 스트링 값으로 파싱한다.
	 * @param color
	 * @return
	 */
	private static String toHexaColor(int color) {
		return String.format("#%06X", 0xFFFFFF & color);
	}	
	
	private void scrollBottom(TextView textView) {
		int lineTop =  textView.getLayout().getLineTop(textView.getLineCount()) ;
		int scrollY = lineTop - textView.getHeight();
		if (scrollY > 0) {
			textView.scrollTo(0, scrollY);
		} else {
			textView.scrollTo(0, 0);
		}
	}
}



댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함