您好,登錄后才能下訂單哦!
怎么在Android中使用TextSwitcher實現(xiàn)自動切換文字功能?相信很多沒有經(jīng)驗的人對此束手無策,為此本文總結(jié)了問題出現(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>
關(guān)于文字定時切換的實現(xiàn):
1.首先寫一個next方法,再這個歌方法中調(diào)用父類的setText()
方法 實現(xiàn)了文字的設(shè)定
2.再主線程中開設(shè)一個性的線程用于圖片的切換 注意:線程中不能直接改變View,所以要發(fā)送小修再Handler對象中改變布局內(nèi)容(文字)
實現(xiàn)如下:
public class MainActivity extends Activity { String[] string = new String[]{ "我愛高數(shù)", "我愛概率論", "我愛計算機網(wǎng)絡(luò)", "我愛操作系統(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 )]); } }
看完上述內(nèi)容,你們掌握怎么在Android中使用TextSwitcher實現(xiàn)自動切換文字功能的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。