本文實例講述了Android開發(fā)實現(xiàn)自動切換文字TextSwitcher功能。分享給大家供大家參考,具體如下:
介紹:
1.TextSwitcher是ViewSwicher的一個子類,繼承了ViewSwicher的所有方法
2.與ViewSwitcher的另一個子類類似,TextSwitcher也有
3.ImageSwitcher不同的是:TextSwitcher的ViewFactory方法的 makeVieW() 必須放回一個TextXiew組件.
具體效果:

放射思維:
如果將其和輪播圖(http://m.survivalescaperooms.com/article/158149.htm)結合 就可以實現(xiàn)帶文字效果的輪播圖。
這里先給出布局文件:
<?xml version="1.0" encoding="utf-8" ?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_horizontal"> <!--定義一個ViewSwitcher并且制定了文本切換時的動畫效果--> <TextSwitcher android:id="@+id/textSwitcher" android:layout_width="match_parent" android:layout_height="wrap_content" android:inAnimation="@android:anim/slide_in_left" android:outAnimation="@android:anim/slide_out_right" android:onClick="next"> </TextSwitcher></RelativeLayout>
關于文字定時切換的實現(xiàn):
1.首先寫一個next方法,再這個歌方法中調用父類的setText()方法 實現(xiàn)了文字的設定
2.再主線程中開設一個性的線程用于圖片的切換 注意:線程中不能直接改變View,所以要發(fā)送小修再Handler對象中改變布局內容(文字)
實現(xiàn)如下:
public class MainActivity extends Activity { String[] string = new String[]{ "我愛高數(shù)", "我愛概率論", "我愛計算機網(wǎng)絡", "我愛操作系統(tǒng)" }; TextSwitcher textSwitcher; int curStr ; Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { next(null); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textSwitcher = (TextSwitcher) findViewById(R.id.textSwitcher); textSwitcher.setFactory(new ViewSwitcher.ViewFactory() { @Override public View makeView() { TextView textView = new TextView(MainActivity.this); textView.setTextSize(40); textView.setTextColor(Color.RED); return textView; } }); new Thread(){ @Override public void run() { while (true){ Message message = handler.obtainMessage(); message.obj = 0; handler.sendMessage(message); try { sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }.start(); } private void next(View scource){ textSwitcher.setText(string[curStr = ( curStr++ % string.length )]); }}更多關于Android相關內容感興趣的讀者可查看本站專題:《Android圖形與圖像處理技巧總結》、《Android開發(fā)入門與進階教程》、《Android調試技巧與常見問題解決方法匯總》、《Android基本組件用法總結》、《Android視圖View技巧總結》、《Android布局layout技巧總結》及《Android控件用法總結》
希望本文所述對大家Android程序設計有所幫助。
新聞熱點
疑難解答