android如何寫一個迴圈文字滾動的TextView,androidtextview
:
在layout中這樣來聲明:
<com.kaixin001.view.ScrollText android:id="@+id/news_statustxt" android:layout_width="wrap_content"android:layout_height="wrap_content" android:paddingLeft="10dp"android:paddingRight="10dp"android:layout_gravity="center_vertical"android:textColor="#000000"android:textSize="16sp"android:hint="@string/news_state_hint"android:inputType="text"/>
activity這樣來調用:
private void initStatus(){ ivState = (ImageView) findViewById(R.id.news_statusinput); //必須使text長度比控制項的寬度大 String s = "dsafsdfsdf(#開心)fsgfdg(#閉嘴)fdgdfgdfgdfgdfgdfgfdgfdgfdgfdgdfg"; newsModel.setStatus(s); String strModel = newsModel.getStatus(); setStateText(strModel); } private void setStateText(String strModel){if(!TextUtils.isEmpty(strModel)){tvState.setStateList(newsModel.getStateList());tvState.setText(strModel); tvState.init(getWindowManager(), handler); tvState.startScroll(); tvState.start(); }}<pre name="code" class="java"> <span style="white-space:pre"></span> public void setStatus(String status){ this.status = status; if(!TextUtils.isEmpty(status)){ stateList = ParseNewsInfoUtil.parseStr(status); } <span style="white-space:pre"></span>}
private Handler handler = new Handler() {@Overridepublic void handleMessage(Message msg) {switch (msg.what) {case ScrollText.TEXT_TIMER:if(tvState != null){tvState.scrollText();}break;default:break;}}};
import java.util.ArrayList;import java.util.Timer;import java.util.TimerTask;import android.content.Context;import android.graphics.Bitmap;import android.graphics.Bitmap.Config;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.graphics.Paint.FontMetrics;import android.graphics.Paint.Style;import android.os.Handler;import android.os.Message;import android.util.AttributeSet;import android.view.WindowManager;import android.widget.TextView;import com.kaixin001.item.LinkInfo;import com.kaixin001.model.StateFaceModel;public class ScrollText extends TextView {public static final int TEXT_TIMER = 100;private float textLength = 0f;// 文本長度private float viewWidth = 0f;private float step = 0f;// 文字的橫座標private float y = 0f;// 文字的縱座標private float temp_view_plus_text_length = 0.0f;// 用於計算的臨時變數private float temp_view_plus_two_text_length = 0.0f;// 用於計算的臨時變數private boolean isStarting = false;// 是否開始滾動private int left = 0;private int right = 0;private Paint paint = null;// 繪圖樣式private String text = "";// 常值內容private Bitmap txtBmp;private Canvas txtCanvas;private FontMetrics fontMetrics;private Timer timer = new Timer();private ArrayList<LinkInfo> stateList;Handler handler;TimerTask task = new TimerTask() {public void run() {if (handler != null && isStarting) {Message msg = Message.obtain();msg.what = TEXT_TIMER;handler.sendMessage(msg);}}};public ScrollText(Context context) {super(context);}public ScrollText(Context context, AttributeSet attrs) {super(context, attrs);}public ScrollText(Context context, AttributeSet attrs, int defStyle) {super(context, attrs, defStyle);}/** *//** * 文本初始化,每次更改常值內容或者文字效果等之後都需要重新初始化一下 */public void init(WindowManager windowManager, Handler handler) {try {this.handler = handler;paint = new Paint();paint.setAntiAlias(true);paint.setStyle(Style.STROKE);paint.setTextSize(getTextSize());paint.setColor(getCurrentTextColor());text = getText().toString();textLength = 0;// textLength = paint.measureText(text);int len = stateList.size();for (int i = 0; i < len; i++) {LinkInfo info = stateList.get(i);if (info.isFace()) {// Emoji排版Bitmap faceBmp = StateFaceModel.getInstance().getSmallFaceIcon(info.getContent());int xLen = faceBmp.getWidth();textLength += xLen + 4;continue;}String strContent = info.getContent();float xLen = paint.measureText(strContent);textLength += xLen;}left = this.getPaddingLeft();right = this.getPaddingRight();step = textLength;fontMetrics = paint.getFontMetrics();y = getPaddingTop();// getTextSize() + getPaddingTop();txtBmp = null;} catch (Exception ex) {ex.printStackTrace();}}public void scrollText() {if (!isStarting) {return;}invalidate();if (viewWidth < textLength) {step += 0.5;if (step > temp_view_plus_two_text_length) {step = textLength;}}}public void setStateList(ArrayList<LinkInfo> stateList) {this.stateList = stateList;}private void setTxtBmp() {if (txtBmp == null && fontMetrics != null) {y = -paint.ascent();// fontMetrics.bottom -// fontMetrics.ascent;//(this.getHeight() -// (int)fontMetrics.ascent)/2;viewWidth = getWidth() - left - right;temp_view_plus_text_length = viewWidth + textLength;temp_view_plus_two_text_length = viewWidth + textLength * 2;txtCanvas = new Canvas();int width = (int) viewWidth;float height = getHeight();txtBmp = Bitmap.createBitmap(width, (int) height, Config.ARGB_8888);txtCanvas.setBitmap(txtBmp);}}/** *//** * 開始滾動 */public void startScroll() {isStarting = true;}/** *//** * 停止滾動 */public void stopScroll() {isStarting = false;// invalidate();}public void start() {timer.schedule(task, 10, 20);}public void stop() {timer.cancel();}@Overridepublic void onDraw(Canvas canvas) {try {setTxtBmp();if (txtBmp == null) {return;}Paint txtPaint = new Paint();txtPaint.setColor(Color.WHITE);txtPaint.setStyle(Style.FILL);txtCanvas.drawRect(0, 0, txtBmp.getWidth(), txtBmp.getHeight(),txtPaint);txtPaint.setAntiAlias(true);txtPaint.setStyle(Style.STROKE);txtPaint.setTextSize(getTextSize());txtPaint.setColor(getCurrentTextColor());float x = 0;// step為text的寬度if (viewWidth < textLength) {x = temp_view_plus_text_length - step;}int len = stateList.size();float curLen = x;for (int i = 0; i < len; i++) {LinkInfo info = stateList.get(i);if (info.isFace()) {// Emoji排版Bitmap faceBmp = StateFaceModel.getInstance().getSmallFaceIcon(info.getContent());int xLen = faceBmp.getWidth();txtCanvas.drawBitmap(faceBmp, curLen + 2, 0, txtPaint);curLen += xLen + 4;continue;}String strContent = info.getContent();strContent = strContent.replaceAll("\n", " ");float xLen = txtPaint.measureText(strContent);//因為x的值一直減少,所以文字可以滾動txtCanvas.drawText(strContent, curLen, y, txtPaint); //<span style="font-family: Arial, Helvetica, sans-serif;">txtCanvas早drawtext.txtBmp上也自然也帶有這些text</span>curLen += xLen;}canvas.drawBitmap(txtBmp, left, 0, paint);} catch (Exception ex) {ex.printStackTrace();}}@Overrideprotected void onSizeChanged(int w, int h, int oldw, int oldh) {super.onSizeChanged(w, h, oldw, oldh);txtBmp = null;setTxtBmp();}}
代碼:http://download.csdn.net/detail/baidu_nod/7736733
我想問一下android中怎使得TextView的文字自動迴圈變換
你需要通過非同步線程更新UI。Android裡實現非同步線程的方法太多了,例如AsyncTask,給個樣本給你吧:
private AsyncTask<Object, Integer, Double> mTask = new AsyncTask<Object, Integer, Double>(){
private int count = 0;
@Override
protected Double doInBackground(Object... params) {
//一秒更新一次
while (mRun) {
try {
Thread.sleep(1000);
publishProgress(++count);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
mTextView.setText(String.valueOf(values[0]));
}
@Override
protected void onPostExecute(Double result) {
//非同步任務執行結束
}
};
在android textView中怎實現文字的縱向的滾動
似乎textview沒有縱向滾動屬性,反正我沒試出來,同樓上,建議用animation實現該效果,不過用不了那麼多,2個就可以了,不知道樓主要在螢幕頂部實現還是其他位置? 剛才沒事做了一個簡單的例子,如果在頂部不用這麼麻煩,寫的特繁瑣,把animation的各種屬性都寫上了,這樣樓主可以根據不同的需要做修改.
package com.mygd;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.LinearLayout;
public class gundongActivity extends Activity implements AnimationListener{
/** Called when the activity is first created. */
int i = 0;
Handler handler = new Handler();
// LinearLayout linearLayout1, linearLayout2, linearLayout3;
// AnimationSet animationSet1, animationSet2, animationSet3;
// TranslateAnimation
// translateAnimation1,translateAnimation2,translateAnimation3;
// AlphaAnimation alphaAnimation1, alphaAnimation2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout linearLayout1 = (LinearLayout) findViewById(R.id.linearLayout1);
LinearLayout linearLayout2 = (LinearLayout) findViewById(R.id.linearLayout2);
LinearLayout linearLayout3 = (LinearLayout) findViewById(R.id.linearLayout3);
AnimationSet animationSet1 = new AnimationSet(true);
AnimationSet animation......餘下全文>>